我正在使用我的应用程序中的自定义钥匙串,我在添加新钥匙链项目后立即阅读钥匙串项目时遇到问题。这是代码示例:
let path = "/tmp/testkeychain_48"
let password = "password"
let serviceName = "service"
let account = "account"
let data = "data".data(using: .utf8)
var keychain: SecKeychain? = nil
var status = SecKeychainCreate(path, UInt32(password.characters.count), password, false, nil, &keychain)
assert(status == errSecSuccess)
var query: [String: AnyObject] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: serviceName as AnyObject,
kSecAttrAccount as String: account as AnyObject,
kSecValueData as String: data as AnyObject,
kSecUseKeychain as String: keychain as AnyObject,
]
var item: CFTypeRef? = nil
status = SecItemAdd(query as CFDictionary, &item)
assert(status == errSecSuccess)
assert(item != nil)
query = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: serviceName as AnyObject,
kSecAttrAccount as String: account as AnyObject,
kSecMatchLimit as String: kSecMatchLimitAll as AnyObject,
kSecUseKeychain as String: keychain as AnyObject,
]
status = SecItemCopyMatching(query as CFDictionary, &item)
assert(status == errSecSuccess)
assert(item != nil)
try? FileManager.default.removeItem(atPath: path)
SecItemAdd(_:_)
返回成功,但SecItemCopyMatching(_:_)
失败,错误为The specified item could not be found in the keychain
。使用默认钥匙串,一切正常。