Miloo
Miloo

Reputation: 127

Save UIImage to UserDefault as Array , Swift

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

}

Upvotes: 1

Views: 2758

Answers (1)

Jake
Jake

Reputation: 13761

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.

Upvotes: 4

Related Questions