Moin Shaikh
Moin Shaikh

Reputation: 7

Save UIImage array in NSUserDefaults

I want to put a UIImage array into UserDefaults and then retrieve it. After that set the retrieved images in an image view. How can I do that?

Upvotes: 0

Views: 1402

Answers (4)

Tejas Ardeshna
Tejas Ardeshna

Reputation: 4371

First of all that is not ideal way to save image in user default but if you want you can do following things

Save

let imageData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(imageData, forKey: "images")

Retrieve

       let imageData = UserDefaults.standard.object(forKey: "images") as? NSData

        if let imageData = imageData {
            let imageArray = NSKeyedUnarchiver.unarchiveObject(with: imageData as Data) as? [UIImage]!
            print(placesArray)
        }

Note: You should save your image in document directory and then save that name array to user default.

Save image in document directory

func saveImageDocumentDirectory(){
        let fileManager = NSFileManager.defaultManager()
        let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("apple.jpg")
        let image = UIImage(named: "apple.jpg")
        print(paths)
        let imageData = UIImageJPEGRepresentation(image!, 0.5)
        fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
    }

Retrieve image

func getImage(name : String){
        let fileManager = NSFileManager.defaultManager()
        let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent(name)
        if fileManager.fileExistsAtPath(imagePAth){
            self.imageView.image = UIImage(contentsOfFile: imagePAth)
        }else{
            print("No Image")
        }
    }

func getDirectoryPath() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

Upvotes: 4

jay patel
jay patel

Reputation: 258

That's really bad idea if you really going to do that. You should save image in DocumentDirectory and save images name in NSUserDefaults.

func saveImages(images:[UIImage]) {

     let fileManager = FileManager.default
     let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) 
     var imagesNames = [String]()


    do {

        if !fileManager.fileExists(atPath: path as String){
            try fileManager.createDirectory(atPath: path as String, withIntermediateDirectories: true, attributes: nil)
        }

     for (index,image) in images.enumarated() {
        let imageName = "Image\(index).jpg"
        let imageData = UIImageJPEGRepresentation(image, 1.0)
        if fileManager.createFile(atPath: paths.appending("/\(file)") as String, contents: imageData, attributes: nil) {
         imagesNames.append(imageName)
        }
      }
     let storage = UserDefaults.standard
     storage.set(imagesNames, forKey: "imagesArray")
     storage.synchronize()

    }catch{
        //Throw Error
    } 
}

Upvotes: 0

Safeen Azad
Safeen Azad

Reputation: 54

You can easily save your image in documentDirectory as below:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first let fileURL = documentDirectory?.appendingPathComponent(yourImageName)

and then, you can give your image to UserDefaults

Upvotes: 0

Syed Sadrul Ullah Sahad
Syed Sadrul Ullah Sahad

Reputation: 1312

Simple approach, convert UIImages to NSData. Then add image data’s into an NSArray. Then save the NSArray into UserDefault. When retrieving the NSArray from UserDefault,use ImageWithData method to render UIImage from the NSArray’s each elements. This is the easiest process if you really one to use UserDefaults for your purpose. Try this yourself.

Upvotes: 0

Related Questions