Search code examples
iosswiftnsuserdefaults

Getting UserDefaults is not returning anything


I have a problem with UserDefaults. I am using UserDefaults(suiteName: UserDefaults.Keys.groupKey) because I also have a Share Extension. This is my setup:

extension UserDefaults:

func setDataSourceArray(data: [Wishlist]?){
    set(try? PropertyListEncoder().encode(data), forKey: Keys.dataSourceKey)
    synchronize()
}

func getDataSourceArray() -> [Wishlist]? {
    if let data = self.value(forKey: Keys.dataSourceKey) as? Data {
        if let dataSourceArray =
            try? PropertyListDecoder().decode(Array < Wishlist > .self, from: data) as[Wishlist] {
                return dataSourceArray
            }
    }
    return nil
}

Calling set:

 // save dataSourceArray in UserDefaults
if let defaults = UserDefaults(suiteName: UserDefaults.Keys.groupKey) {
    defaults.setIsLoggedIn(value: true)
    defaults.setDataSourceArray(data: dataArray as? [Wishlist])
    defaults.setDropOptions(dropOptions: self.dropOptions)
    defaults.synchronize()
} else {
    print("error Main")
}

Setting works perfectly fine. No error.

Calling get:

if let defaults = UserDefaults(suiteName: UserDefaults.Keys.groupKey) {
        print(defaults.isLoggedIn())
        if defaults.isLoggedIn(){
            if let data = defaults.getDataSourceArray(){
                
                defaults.synchronize()
                print(data[0].name)

            } else {
                print("Error getting dataSourceArray")
            }
        } else {
            print("yeet")
        }
        
    } else {
        print("error 1")
}

This always prints: "Error getting dataSourceArray". I am stuck and have no idea what Im doing wrong here, so Im happy for every help!

UPDATE:

I noticed a weird behavior which I can not explain: when in Calling set I only call defaults.setDataSourceArray(data: dataArray as? [Wishlist]) without setting isLoggedIn and dropOptions it works fine?! Can anyone explain that to me?


Solution

  • I solved the problem.. Stupid beginners problem. When setDropOptions inside UserDefaults I used the key from dataSourceArray. Fixed that and its working now. Thanks for everyone who tried to help anyway :)