Save array in Keychain
Asked Answered
V

3

5

I am trying to save an array in keychain but I can't convert an array to NSData. I have my function prepared for saving strings but I don't know how to get a valueData from an array.

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)")
    }

}
Vito answered 3/2, 2016 at 16:44 Comment(0)
I
5

You can use NSKeyedArchiver.archivedDataWithRootObject on your array when saving, and NSKeyedUnarchiver.unarchiveObjectWithData when loading.

I answered 3/2, 2016 at 16:50 Comment(0)
O
12

You can use NSKeyedArchiver and NSKeyedUnarchiver to convert NSArrays and NSDictionaries to data:

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

let arrayFromData = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! NSArray
Orlandoorlanta answered 3/2, 2016 at 16:53 Comment(0)
I
5

You can use NSKeyedArchiver.archivedDataWithRootObject on your array when saving, and NSKeyedUnarchiver.unarchiveObjectWithData when loading.

I answered 3/2, 2016 at 16:50 Comment(0)
E
2

Providing the solution with the new methods in swift 5 code. The provided answers are using deprecated methods.

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");
    }
Etan answered 16/12, 2020 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.