Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save array in Keychain

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

}
like image 766
angeldev Avatar asked Dec 05 '22 19:12

angeldev


1 Answers

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
like image 192
Danny Bravo Avatar answered Dec 10 '22 12:12

Danny Bravo