您需要从钥匙串中删除现有项目。
这是我的示例代码,使用 Apple 示例代码。
您可以从Apple获取示例代码
Apple 建议您在使用前获取凭据的状态以检查是否撤销,如果发生这种情况,请删除任何本地信息
struct KeychainItem {
init(service: String, account: String, accessGroup: String? = nil) {
self.service = service
self.account = account
self.accessGroup = accessGroup
}
static func deleteUserIdentifierFromKeychain() {
do { //please change service id to your bundle ID
try KeychainItem(service: "com.example.apple-samplecode", account: "userIdentifier").deleteItem()
} catch {
print("Unable to delete userIdentifier from keychain")
}
}
func deleteItem() throws {
// Delete the existing item from the keychain.
let query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemDelete(query as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError }
}
钥匙串查询
keychainQuery 来自苹果示例代码。
private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String: AnyObject] {
var query = [String: AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = service as AnyObject?
if let account = account {
query[kSecAttrAccount as String] = account as AnyObject?
}
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
}
return query
}