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)")
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With