0
這是我的代碼:Alamofire不能立即保存圖像到磁盤
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
_ = Alamofire.download("http://www.sample.com/images/sample.png", to: destination)
let documentsDirectory = FileManager.SearchPathDirectory.documentDirectory
let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(documentsDirectory, userDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("sample.png")
if let image = UIImage(contentsOfFile: imageURL.path) {
self.sampleImage.image = image
}
}
我第一次運行該代碼,圖像無;所以我在下載時設置了一個斷點,剛剛通過下載代碼,檢查了磁盤上的目錄並且圖像沒有保存到文件(這就是爲什麼圖像是零)。在運行UIViewContoller
類中的所有代碼之後,該文件已成功保存到磁盤,並且第二次導航到ViewController時加載了該映像。
有什麼方法可以下載圖像,立即保存到磁盤,然後顯示圖像?
我試過把下載代碼放在viewWillAppear
和從viewDidLoad
的磁盤代碼加載。我也嘗試用完成塊創建一個方法,並將下載代碼放入完成塊中。
完美!謝謝你的幫助! – Sicypher