如何处理已弃用的函数 'unarchiveObject(with:)'?

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

尝试从这里实现 KeychainWrapper:https://github.com/jrendel/SwiftKeychainWrapper 它运行良好,但在一段代码中我出错了:“'unarchiveObject(with:)' 在 iOS 12.0 中已被弃用:改为使用 +unarchivedObjectOfClass:fromData:error:”

我试着按照 看起来很相似但没有成功。

这段代码在这里:

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

这是更新后的版本:

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

感谢提示Himanshu Patel它对我有用。这是更新后的代码:

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

您可以通过以下方式进行...

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

// 从Userdefault获取数据

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