Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an array of structs to userDefaults

Tags:

ios

swift

In my app I have the user take a picture of an item of clothing, then give it a tag describing what type it is (pants, shirt, shoes, etc). I then take this info and save it into a struct Item. After that, I put the recently made Item into an array of Items. I'm struggling with how to save this array of Items to UserDefaults so I can load back when the app is closed.

I've tried adding Codable to my struct but that just brought up more issues. I wanted to update the UserDefaults every time the user adds a new item to the array. I plan to do it in saveItemButton function (shown below).

var itemsArray: [Item] = []

//.pants, .shirt, .shoes, .hat, .extra, .jacket
var itemType: clothingType? = nil

@IBAction func saveItemButton(_ sender: Any) {
    if(itemType != nil && imageView.image != nil){
        saveImage(imageName: ("item" + "\(itemsArray.count)"))
        let item = Item(itemType: itemType!, itemName: ("item" + "\(itemsArray.count)"))


        itemsArray.append(item)

        //let defaults = UserDefaults.standard
        //defaults.set(itemsArray, forKey: "SavedItemArray")
    }
}

Here is my struct in a separate swift file:

import Foundation
import UIKit


struct Item{
    var itemType: clothingType
    var itemName: String
    //var itemImage: UIImage?
}

enum clothingType{
    case pants
    case shirt
    case jacket
    case shoes
    case hat
    case extra
}

And here is where I would load the itemArray from UserDefaults:

override func viewDidLoad() {
    super.viewDidLoad()
    //        let defaults = UserDefaults.standard
    //        let array = defaults.array(forKey: "SavedItemArray")  as? [Item] ?? [Item]()
    //        itemsArray = array
}

Looking to be able to save and load an array of Item to UserDefaults.

like image 333
Walker Avatar asked Apr 23 '19 16:04

Walker


People also ask

Can we store array in UserDefaults?

You can only store arrays of strings, numbers, Date objects, and Data objects in the user's defaults database. Let's take a look at an example. We access the shared defaults object through the standard class property of the UserDefaults class.

How data is stored in UserDefaults?

Updating the Prospects initializer so that it loads its data from UserDefaults where possible. Adding a save() method to the same class, writing the current data to UserDefaults . Calling save() when adding a prospect or toggling its isContacted property.

Is UserDefaults synchronous?

Yes it is synchronous .


1 Answers

Like this:

struct Item : Codable {
    var itemType: clothingType
    var itemName: String
}

enum clothingType : String, Codable {
    case pants
    case shirt
    case jacket
    case shoes
    case hat
    case extra
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let defaults = UserDefaults.standard
        if let data = defaults.data(forKey: "SavedItemArray") {
            let array = try! PropertyListDecoder().decode([Item].self, from: data)
        }
    }
}

Of course I suppose now you're wondering how we got the data into user defaults in the first place. Like this:

    let array : [Item] = // whatever
    if let data = try? PropertyListEncoder().encode(array) {
        UserDefaults.standard.set(data, forKey: "SavedItemArray")
    }
like image 51
matt Avatar answered Sep 28 '22 15:09

matt