简体   繁体   中英

storing background images in userdefaults

I need to be able to set the background image for this button. I need to store this so after the app closes the background image is the same.

eventsFirstButton.backgroundColor = UIColor(patternImage: UIImage(named: "events")!)

You could just save the state:

Correct answer:

UserDefaults.standard.set(true, forKey: "TestAnswer1")
//If the answer is incorrect set to false

On load:

 if UserDefaults.standard.bool(forKey: "TestAnswer1") {
      view.backgroundColor = UIColor.green
      // or any other logic
 } else {
      view.backgroundColor = UIColor.red
      // or any other logic
 } 

It's better to save it as base64string , you don't want to store large value to UserDefaults.

To encode UIImage use this:

let image = UIImage()
let data = image.pngData()
let imageBase64String = data?.base64EncodedString()
UserDefaults.standard.set(imageBase64String, forKey: "encodedImage")

And for decoding and retrieving UIImage use this:

if let imageBase64String = UserDefaults.standard.value(forKey: "encodedImage"),
    let url = URL(string: String(format:"data:application/octet-stream;base64,%@",imageBase64String))
{
    do
    {
        let data =  try Data(contentsOf: url) 
        let image = UIImage(data: data)
    }
    catch let error
    {
        print("Error decoding image")    
    }
}

If you really need to save the PNG, JPEG images locally, use CoreData to store them on the device.

You can use UserDefaults to save your image

Save

if let image = eventsFirstButton.imageView?.image {
            let imageData = image.pngData()
            UserDefaults.standard.set(imageData, forKey: "imageData")
        }

Retrieve

if let imageData = UserDefaults.standard.data(forKey: "imageData") {
            print("IMG data: ", imageData)
            // your code here
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM