Search code examples
iosswiftuiimagedata-persistence

Save image from URL and make it persist IOS Swift


I would like to save images from a URL and then use them inside my app.

I saved them in variables but how can I make them persist until the user deletes the app ?

Here is the code for saving images in variables

    let backgroundURL:NSURL? = NSURL(string: "http://i.imgur.com/4AiXzf8.jpg")
    DispatchQueue.global(qos: .userInitiated).async {
        let backgroundData:NSData? = NSData(contentsOf: backgroundURL as! URL)
        DispatchQueue.main.async {
            if (backgroundData != nil) {
                background = UIImage(data: backgroundData! as Data   
            }
        }
    }

How can I save the background image to persist ?

Thank you!


Solution

  • For Swift 3

    // Assuming background is UIImage
    if let image = background {
        if let data = UIImagePNGRepresentation(image) {
            let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
            try? data.write(to: filename)
        }
    }
    

    That call to getDocumentsDirectory()

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentsDirectory = paths[0]
        return documentsDirectory
    }