如何在Mac Catalyst应用程序中使用钥匙串(Keychain)?

6

我无法在Mac Catalyst应用程序中写入/读取Keychain,它分别返回错误码34018和25300。有没有办法使Keychain在Catalyst应用程序中在Mac上工作?

Xcode: 11.0, MacOS: 10.15

这是一个示例代码,在iOS上运行正常,但在Mac上无法正常运行。该代码会打印“我的秘密蜜蜂”,以表示我们已成功将此文本写入Keychain并从中读取。

override func viewDidLoad() {
  super.viewDidLoad()

  let itemKey = "My key"
  let itemValue = "My secretive bee "
  deleteFromKeychain(itemKey: itemKey)
  addToKeychain(itemKey: itemKey, itemValue: itemValue)
  readFromKeychain(itemKey: itemKey)
}

func deleteFromKeychain(itemKey: String) {
  let queryDelete: [String: AnyObject] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: itemKey as AnyObject,
  ]

  let resultCodeDelete = SecItemDelete(queryDelete as CFDictionary)

  if resultCodeDelete != noErr {
    print("Error deleting from Keychain: \(resultCodeDelete)")
  }
}

func addToKeychain(itemKey: String, itemValue: String) {
  guard let valueData = itemValue.data(using: String.Encoding.utf8) else {
    print("Error saving text to Keychain")
    return
  }

  let queryAdd: [String: AnyObject] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: itemKey as AnyObject,
    kSecValueData as String: valueData as AnyObject,
    kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlocked,
  ]

  let resultCode = SecItemAdd(queryAdd as CFDictionary, nil)

  if resultCode != noErr {
    print("Error saving to Keychain: \(resultCode)")
  }
}

func readFromKeychain(itemKey: String) {
  let queryLoad: [String: AnyObject] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: itemKey as AnyObject,
    kSecReturnData as String: kCFBooleanTrue,
    kSecMatchLimit as String: kSecMatchLimitOne,
  ]

  var result: AnyObject?

  let resultCodeLoad = withUnsafeMutablePointer(to: &result) {
    SecItemCopyMatching(queryLoad as CFDictionary, UnsafeMutablePointer($0))
  }

  if resultCodeLoad == noErr {
    if let result = result as? Data,
      let keyValue = NSString(data: result,
                             encoding: String.Encoding.utf8.rawValue) as? String {

      // Found successfully
      print(keyValue)
    }
  } else {
    print("Error loading from Keychain: \(resultCodeLoad)")
  }
}
1个回答

14

我在 Xcode 的签名和能力部分启用了钥匙串共享功能,现在我可以在钥匙串中存储值了。


谢谢你!我修改了代码,现在只需添加这些功能就可以正常工作了。感谢你,你救了我的一天! - Yogesh Patel
你启用了钥匙串访问组吗? - Angelru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接