【发布时间】:2017-07-24 05:28:16
【问题描述】:
这是我的代码:
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 中。我还尝试创建一个带有完成块的方法,并将下载代码放在完成块中。
【问题讨论】: