Save image from URL and make it persist IOS Swift

2.1k views Asked by At

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!

2

There are 2 answers

2
Museer Ahamad Ansari On BEST ANSWER

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
}
3
Devang Tandel On

I would suggest you to store image in your document directory the below code you will be able to use after you downloaded image and converted as UIImage from NSData

Swift 2.3

let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
// Name of Image you want to store
let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("ImageName.jpg")

if !NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) {
    if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(fileURL.path!, atomically: true) {
        print("Image saved")
    } else {
        print("error saving Image")
    }
} else {
    print("Image name already exists")
}

And here is how you can get image

let fileManager = NSFileManager.defaultManager()
let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent("imageName.jpg")

if fileManager.fileExistsAtPath(imagePAth){
let myImage: UIImage = UIImage(contentsOfFile: imagePAth)
}
else{
print("No Such Image")
}