Search code examples
iosswiftkeychainnskeyedunarchiver

How to deal with deprecated function 'unarchiveObject(with:)'?


Try to implement KeychainWrapper from here: https://github.com/jrendel/SwiftKeychainWrapper It is functioning well but in one piece of code I get mistake: "'unarchiveObject(with:)' was deprecated in iOS 12.0: Use +unarchivedObjectOfClass:fromData:error: instead"

I tried to follow the discussion which seems to be similar but wasn't successful.

The piece of code is here:

open func object(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> NSCoding? {
    guard let keychainData = data(forKey: key, withAccessibility: accessibility) else {
        return nil
    }

    return NSKeyedUnarchiver.unarchiveObject(with: keychainData) as? NSCoding

How to NSKeyedUnarchiver.unarchiveObject

Here is the updated version:

open func object(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil) -> NSCoding? {
guard let keychainData = data(forKey: key, withAccessibility: accessibility) else {
    return nil
}

let result = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(keychainData) as? NSCoding

return result

Solution

  • You can do this in following way...

    let result = jsonDict["result"] as? NSDictionary ?? [:]
    let data = try! NSKeyedArchiver.archivedData(withRootObject: result, requiringSecureCoding: false)
    UserDefaults.standard.set(data, forKey: "currentUser")
    

    // Get data from Userdefault

    let result = UserDefaults.standard.data(forKey: "currentUser")
        if result != nil{
        let dict = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(result!) as? NSDictionary ?? [:]
        print("Current User Details : - \(dict)")
    }