Search code examples
ioskeychain

secItemAdd keep return -50 error in swift


Keep getting -50 when trying to add an item in security chain.

    var query = [String:AnyObject]()
    query[kSecClass as String] = kSecClassGenericPassword
    query[kSecAttrAccount as String] = "a"
    query[kSecValueData as String] = "b"
    let result = SecItemAdd(query as CFDictionary, nil);

result is -50. Can not figure out why, need help.. thanks in advance.


Solution

  • I believe the value for the kSecValueData key needs to be an NSData, not a String or NSString. Try encoding your string to data (with e.g. UTF-8 encoding). Untested snippet:

    query[kSecValueData as String] = "b".dataUsingEncoding(NSUTF8StringEncoding)
    

    For future reference, the error code -50 corresponds to errSecParam, which the SecBase.h header documents as meaning: "One or more parameters passed to a function were not valid." If you see this error again, try changing the values that you're passing in with your query dictionary.