ios - swift 图片从URL下载到本地存储

标签 ios swift download uiimage

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/

相关文章:

iOS 应用程序数据库选项

iOS Core Data - 将相关数据添加到实体

ios - 如何在 collectionview 单元格中的 didselect 上显示不同的 View Controller

swift - 将 "generic"对象图(字典、数组、字符串等)保存为默认值而不进行编码?

ios - 在 iOS 中,动画 View 在手动调用 segue 后返回到其原始状态

ios - Objective-C 中类似 Photoshop 的曲线工具

Swift:如何在函数执行之外终止函数

java - 在 Java servlet 中创建和下载 CSV 文件

html - <audio> 隐藏下载控件

android - 使用 DefaultHTTPClient 和抢先身份验证下载文件