2017-03-03 69 views
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的磁盤代碼加載。我也嘗試用完成塊創建一個方法,並將下載代碼放入完成塊中。

回答

1

Alamofire.download函數是異步的,所以它將開始下載並且您的代碼將會繼續立即執行。

您應該使用該函數的處理程序來處理文件,只要它被下載。

Alamofire.download("http://www.sample.com/images/sample.png", to: destination).responseData { response in 
    if let data = response.result.value { 
     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 
      } 
     } 
    } 
} 
+0

完美!謝謝你的幫助! – Sicypher