【问题标题】:swift Image from URL download to local storage从 URL 下载到本地存储的快速图像
【发布时间】:2018-04-28 23:54:16
【问题描述】:
DispatchQueue.global().async {
     let data = try? Data(contentsOf: url!)
     DispatchQueue.main.async {
          let img = UIImage(data: data!)
     }
}

如何将 Data(contentsOf: url!) 返回的图像保存到本地 iPhone 存储中,以确保用户每次启动应用程序时都不需要下载? p>

我知道有些应用程序每次更新都会下载大量数据和图像,以节省从 App Store 下载的应用程序的大小。这怎么可能?

另一件事是,图像将在 SKSpriteNode 中使用,而不是在 UIImageView 中。无需急于显示图像,因为它们将在游戏加载时下载。

【问题讨论】:

    标签: ios swift download uiimage


    【解决方案1】:

    您不应使用Data(contentsOf:) 初始化程序来获取非本地资源。如果您尝试将其保存到磁盘,则无需将其下载到内存中。您可以使用 URLSession downloadTask 方法将文件异步直接下载到磁盘:


    import UIKit
    import PlaygroundSupport
    PlaygroundPage.current.needsIndefiniteExecution = true
    
    let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    
    if let url = URL(string: "https://i.stack.imgur.com/xnZXF.jpg") {
        URLSession.shared.downloadTask(with: url) { location, response, error in
            guard let location = location else {
                print("download error:", error ?? "")
                return
            }
            // move the downloaded file from the temporary location url to your app documents directory
            do {
                try FileManager.default.moveItem(at: location, to: documents.appendingPathComponent(response?.suggestedFilename ?? url.lastPathComponent))
            } catch {
                print(error)
            }
        }.resume()
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多