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: "/image/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()
}
关于ios - swift 图片从URL下载到本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082100/