Saving an image array with UserDefaults

前端 未结 2 1480
北海茫月
北海茫月 2020-12-11 21:00

I have an app where the user takes a picture and once the picture is taken it should be saved to UserDefaults. I keep getting this error:

\"can         


        
2条回答
  •  失恋的感觉
    2020-12-11 21:20

    edit/update:

    Xcode 10.1 • Swift 4.2.1 or later

    It is not a good idea to store images at NSUserDefaults but if you really want to do it you need to store is as NSData.

    The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects

    I recommend saving it locally to disk at the Documents Folder. If you really want to save it to NSUserDefaults, I recommend using just for small images and do it at your own risk :) You can do as follow:

    extension UserDefaults {
        func set(image: UIImage?, quality: CGFloat = 0.5, forKey defaultName: String) {
            guard let image = image else {
                set(nil, forKey: defaultName)
                return
            }
            set(image.jpegData(compressionQuality: quality), forKey: defaultName)
        }
        func image(forKey defaultName:String) -> UIImage? {
            guard
                let data = data(forKey: defaultName),
                let image = UIImage(data: data)
            else  { return nil }
            return image
        }
        func set(images value: [UIImage]?, forKey defaultName: String) throws {
            guard let value = value else {
                removeObject(forKey: defaultName)
                return
            }
            try set(NSKeyedArchiver.archivedData(withRootObject: value, requiringSecureCoding: false), forKey: defaultName)
        }
        func images(forKey defaultName: String) throws -> [UIImage] {
            guard let data = data(forKey: defaultName) else { return [] }
    
            let object = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data)
            return object as? [UIImage] ?? []
        }
    }
    

    Testing:

    let image = UIImage(data: try! Data(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!))!
    UserDefaults.standard.set(image: image, forKey: "imageKey")
    if let loadedImage = UserDefaults.standard.image(forKey: "imageKey") {
        print(loadedImage.size)  // "(719.0, 808.0)"
    }
    
    let images = [image, image]
    try? UserDefaults.standard.set(images: images, forKey: "imagesKey")
    if let loadedImages = try? UserDefaults.standard.images(forKey: "imagesKey") {
        print(loadedImages.count)  // 2
    }
    

提交回复
热议问题