Adding item to keychain using Swift

前端 未结 7 1954
栀梦
栀梦 2020-12-28 08:45

I\'m trying to add an item to the iOS keychain using Swift but can\'t figure out how to type cast properly. From WWDC 2013 session 709, given the following Objective-C code:

7条回答
  •  半阙折子戏
    2020-12-28 09:32

    In order to get this to work, you need to access the retained values of the keychain constants instead. For example:

    let kSecClassValue = kSecClass.takeRetainedValue() as NSString
    let kSecAttrAccountValue = kSecAttrAccount.takeRetainedValue() as NSString
    let kSecValueDataValue = kSecValueData.takeRetainedValue() as NSString
    let kSecClassGenericPasswordValue = kSecClassGenericPassword.takeRetainedValue() as NSString
    let kSecAttrServiceValue = kSecAttrService.takeRetainedValue() as NSString
    let kSecMatchLimitValue = kSecMatchLimit.takeRetainedValue() as NSString
    let kSecReturnDataValue = kSecReturnData.takeRetainedValue() as NSString
    let kSecMatchLimitOneValue = kSecMatchLimitOne.takeRetainedValue() as NSString
    

    You can then reference the values in the MSMutableDictionary like so:

    var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])
    

    I wrote a blog post about it at: http://rshelby.com/2014/08/using-swift-to-save-and-query-ios-keychain-in-xcode-beta-4/

    Hope this helps!

    rshelby

提交回复
热议问题