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()
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句