Search code examples
iosswiftnsuserdefaultsuicolornskeyedarchiver

Archive and Unarchive an array of UIColours to NSUserDefaults in iOS 12?




I'm still new to Swift and i'm trying archive and unarchive an array of UIColours to NSUserDefaults. I'm aware that in ios 12 i need to use unarchivedObject(ofClass:from:) - but i'm not sure how to use that.

I've tried to follow this question: Unarchive Array with NSKeyedUnarchiver unarchivedObject(ofClass:from:) but i think i'm doing something wrong.

Here is the code i am trying:

let faveColoursArray = [colour1, colour2]

private func archiveColours() -> Data {

    do {
        let data = try NSKeyedArchiver.archivedData(withRootObject: faveColoursArray, requiringSecureCoding: false)

        return data
    } catch {
        fatalError("can't encode data.")
    }


}


   func loadColours() -> [UIColor]? {

      guard let unarchivedObject = UserDefaults.standard.data(forKey: "faveColours") else {
          return nil
      }

      do {
          guard let array = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: unarchivedObject) else {
            fatalError("Can't load colours.")
        }
        return array
      } catch {
          fatalError("Can't load colours.")
      }

  }

Thankyou


Solution

  • You can use unarchiveTopLevelObjectWithData(_:):

    func loadColours() -> [UIColor]? {
        guard let unarchivedObject = UserDefaults.standard.data(forKey: "faveColours") else {
          return nil
        }
    
        do {
          guard let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(unarchivedObject) as? [UIColor] else {
            fatalError("Can't load colours.")
          }
          return array
        } catch {
          fatalError("Can't load colours.")
        }
    
    }