Ryann786
Ryann786

Reputation: 309

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

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?

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?

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.

Upvotes: 4

Views: 6929

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236538

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.sstatic.net/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()
}

Upvotes: 5

Related Questions