提问者:小点点

如何在Swift5中将UIImage保存为UserDefaults


我试图将用户图像保存为userDefaults,但我总是收到错误“Thread 1:”尝试插入非属性列表对象(函数)以进行键保存“这是我的代码

import UIKit

class productSelectionPage: UIViewController {
    @IBOutlet weak var productImageView: UIImageView!


    override func viewDidLoad() {
        super.viewDidLoad()

        // Save image
        let image = UIImage(named: "user")
        let imageData = UIImage.jpegData(image)
        UserDefaults.standard.setValue(imageData, forKey: "savedImage")

    }
    @IBAction func offerButtonTapped(_ sender: UIButton) {
        // present image
        let imageData = UserDefaults.standard.object(forKey: "savedImage")
        let image = UIImage(data: (imageData as! NSData) as Data)
        productImageView.image = image
        // crash

        
        
    }
    

}

共1个答案

匿名用户

尝试像这样使用PropertyListEncoder()和Decoder:

func saveImage() {
    guard let data = UIImage(named: "image").jpegData(compressionQuality: 0.5) else { return }
    let encoded = try! PropertyListEncoder().encode(data)
    UserDefaults.standard.set(encoded, forKey: "KEY")
}

func loadImage() {
     guard let data = UserDefaults.standard.data(forKey: "KEY") else { return }
     let decoded = try! PropertyListDecoder().decode(Data.self, from: data)
     let image = UIImage(data: decoded)
}