swift 图片来自 URL 下载到本地存储

swift Image from URL download to local storage

DispatchQueue.global().async {
     let data = try? Data(contentsOf: url!)
     DispatchQueue.main.async {
          let img = UIImage(data: data!)
     }
}

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

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

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

您不应使用 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()
}