如何在 Mac 上的 Mac Catalyst 应用程序中使用钥匙串?

Posted

技术标签:

【中文标题】如何在 Mac 上的 Mac Catalyst 应用程序中使用钥匙串?【英文标题】:How can I use Keychain in Mac Catalyst app on Mac? 【发布时间】:2020-02-25 04:37:06 【问题描述】:

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

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】:

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

【讨论】:

非常感谢你。我更改了代码和代码,现在只需添加这些功能,它就可以正常工作了。谢谢,你拯救了我的一天!

以上是关于如何在 Mac 上的 Mac Catalyst 应用程序中使用钥匙串?的主要内容,如果未能解决你的问题,请参考以下文章

iOS:Mac Catalyst,在其他 Mac 上测试 iOS 应用

如何在 Mac Catalyst 应用程序中禁用默认键盘导航?

Mac Catalyst 应用程序如何处理生命周期转换?

Mac Catalyst 无法使用 pressesBegan 覆盖捕获 .command 键修饰符

如何在 Mac Catalyst 中检测窗口大小调整?

如何修复“读写数据沙箱:使用 Mac Catalyst 时出错”