0

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?

0

4 Answers 4

4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Work fine on Swift 4.2
0

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

Comments

0

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.

Comments

0

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

4 Comments

but i have multiple images in array, which want show in imageview so i can in DocumentDirectory
can you share your code here because i am new in development
Check out. I modified Answer.
And after set in user default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.