swift2 在钥匙串中保存阵列

hm2xizp9  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(195)

我尝试在keychain中保存数组,但无法将数组转换为NSData。我已准备好保存字符串的函数,但我不知道如何从数组中获取valueData

func add(key: String, value: AnyObject) {

    let service = NSBundle.mainBundle().bundleIdentifier!

    let valueData: NSData! = value.dataUsingEncoding(NSUTF8StringEncoding,
        allowLossyConversion: false)

    let secItem = [
        kSecClass as String : kSecClassGenericPassword as String,
        kSecAttrService as String : service,
        kSecAttrAccount as String : key,
        kSecValueData as String : valueData
    ]
    let result: UnsafeMutablePointer<AnyObject?> = nil
    let status = Int(SecItemAdd(secItem, result))

    if status == Int(errSecDuplicateItem){
        self.update(key, newData: value)
    } else {
        print("An error occurred with code \(status)")
    }

}
eagi6jfj

eagi6jfj1#

您可以使用NSKeyedArchiver和NSKeyedUnarchiver将NSArrays和NSDicaries转换为数据:

let array : NSArray = ["one", "two"]
let data = NSKeyedArchiver.archivedDataWithRootObject(array)

let arrayFromData = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSArray
b91juud3

b91juud32#

您可以在保存时对数组使用NSKeyedArchiver.archivedDataWithRootObject,在加载时使用NSKeyedUnarchiver.unarchiveObjectWithData

ddarikpa

ddarikpa3#

用swift 5代码提供带有新方法的解决方案。提供的答案使用的是过时的方法。

let array : NSArray = ["one", "two"]

    var data = Data()
    do {
        data = try NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: true)
    } catch {
        print("archivedData Error");
    }

    do {
        let arrayFromData = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: data)
    } catch {
        print("unarchivedObject Error");
    }

相关问题