将图像从URL下载到本地存储 [英] swift Image from URL download to local storage

查看:81
本文介绍了将图像从URL下载到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何将 Data(contentsOf:url!)返回的图像保存到本地iPhone存储,以确保此操作

How do I save the image returned from the Data(contentsOf: url!) to local iPhone storage to ensure this doesn't need to be downloaded each time the user starts the app?

我知道有些应用程序每次下载都会下载大量数据和图像以节省应用程序的大小,而不必每次下载该应用程序?从App Store下载的。

I know some apps download lots of data and images each update to save on the size of the App that is downloaded from the App Store. How is this possible?

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

The other thing is, the image will be used in an SKSpriteNode not in a UIImageView. There is no rush to display the images as they will be downloaded whilst the game is loading.

推荐答案

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

You shouldn't use Data(contentsOf:) initializer to fetch non local resources. If you are trying to save it to disk there is no need to download it to memory. You can use URLSession downloadTask method to download your file asynchronously direct to disk:

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()
}

这篇关于将图像从URL下载到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆