【问题标题】:Alamofire Not Immediately Saving Image to DiskAlamofire 不会立即将图像保存到磁盘
【发布时间】: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 中。我还尝试创建一个带有完成块的方法,并将下载代码放在完成块中。

【问题讨论】:

    标签: ios swift alamofire


    【解决方案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
                }
            }
        }
    }
    

    【讨论】:

    • 完美!谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2018-02-26
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多