Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 907
Roman Avatar asked Sep 10 '25 22:09

Roman


2 Answers

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)")
}
like image 144
Himanshu Patel Avatar answered Sep 13 '25 12:09

Himanshu Patel


Thanks for the hint Himanshu Patel It worked for me. Here is the updated code:

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
like image 41
Roman Avatar answered Sep 13 '25 11:09

Roman