1

I have one UiTableView , I need to have one Array Data Saving UIimage for Temporary time .

I Think if I use UserDefault it's not bad solution but I don't know how save in UserDefault I know I don't use .stringArray I don't know how can I Save Image in Array Default

struct Constants {

    static let myKeyImage = "myKeyIMG”

}


 var arrayiMG = [String]()
  self.defaults.stringArray(forKey: Constants.myKeyImage)


if (self.defaults.stringArray(forKey: Constants.myKeyImage) != nil)
{
arrayUrl = self.defaults.stringArray(forKey: Constants.myKeyURL)!
}

I want to save in .png or jpg Like this

func plane(from anchor: ARPlaneAnchor) -> SCNNode {
    if (`extension`.lowercased() == "png") {
        data = UIImagePNGRepresentation(image)
    }
    else if (`extension`.lowercased() == "jpg") {
        data = .uiImageJPEGRepresentation()
    }

}
7
  • extension is really awful name Commented Feb 11, 2018 at 21:36
  • @Vyacheslav if it's possible please give me one good way and one good array data Commented Feb 11, 2018 at 21:43
  • "I Think if I use UserDefault it's not bad solution" - it is a bad solution. UserDefaults is not meant to store lots data. Commented Feb 11, 2018 at 22:41
  • @rmaddy I need to save for Temporary time and after I need to delete the image array do you have better solutions ? Commented Feb 11, 2018 at 23:37
  • As @Jake stated at the end of his answer, write the images to files. Commented Feb 11, 2018 at 23:53

1 Answer 1

4

Something like this would work:

extension UserDefaults {
    func imageArray(forKey key: String) -> [UIImage]? {
        guard let array = self.array(forKey: key) as? [Data] else {
            return nil
        }
        return array.flatMap() { UIImage(data: $0) }
    }

    func set(_ imageArray: [UIImage], forKey key: String) {
        self.set(imageArray.flatMap({ UIImagePNGRepresentation($0) }), forKey: key)
    }
}

Usage:

let imageArray = [image1, image2, image3]
UserDefaults.standard.set(imageArray, forKey: "images")

let images = UserDefaults.standard.imageArray(forKey: "image")

However, I wouldn't recommend storing an array of images in UserDefaults. Storing the images as files would probably be more appropriate. You could then store their paths in UserDefaults.

Sign up to request clarification or add additional context in comments.

Comments

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.