Keychain is simply a database stored in the file system, a user or application can create as many keychains as desired.
varitem=[String: AnyObject]()- Query keychain item with service name, account name and access group. Set keychain type, this keychain is a generic password.
item[kSecClass asString]= kSecClassGenericPassword
item[kSecAttrService asString]= service asAnyObject?item[kSecAttrAccount asString]= account asAnyObject?item[kSecAttrAccessGroup asString]= accessGroup asAnyObject?- Save password. Convert password string to data type add create a dictionary to save as a new keychain item.
letencodedPassword= password.data(using:String.Encoding.utf8)!
item[kSecValueData asString]= encodedPassword asAnyObject?letstatus=SecItemAdd(item asCFDictionary,nil)- Read password. You could get attributes of the first match only or all items. Also you could get return attribute and data. Finally fetch the password in parsed password string with "SecItemCopyMatching" method.
item[kSecMatchLimit asString]= kSecMatchLimitOne
item[kSecReturnAttributes asString]= kCFBooleanTrue
item[kSecReturnData asString]= kCFBooleanTrue
varqueryResult:AnyObject?letstatus=withUnsafeMutablePointer(to:&queryResult){SecItemCopyMatching(query asCFDictionary,UnsafeMutablePointer($0))}letpasswordData=item[kSecValueData asString]as?Data,letpassword= String(data: passwordData, encoding: String.Encoding.utf8)- Update keychain item. You should update new item, likes password and account with "SecItemUpdate" method.
letstatus=SecItemUpdate(item asCFDictionary, attributesToUpdate asCFDictionary)- Delete keychain item. It's very easy.
letstatus=SecItemDelete(item asCFDictionary)- Finally, you just need to throws an error if an unexpected status was returned.
guard status != errSecItemNotFound else{throw PwdKeychainError }guard status == noErr else{throwPwdKeychainError.unhandledError(status: status)}By default, only the app that created an item can access it in the future. But Keychain Services does more than simply check the identity of an app. Instead, it compares a keychain item’s access group, recorded as the kSecAttrAccessGroup attribute, with the list of access groups to which an app belongs. If one of the app’s access groups matches the keychain item’s group, access is granted. Similarly, Keychain Services allows an app to create keychain items with the kSecAttrAccessGroup attribute set to any of the app’s own access groups.