oblador / react-native-keychain

:key: Keychain Access for React Native
MIT License
3.12k stars 515 forks source link

Using it together with native iOS project #621

Open CyberMew opened 5 months ago

CyberMew commented 5 months ago

Is it possible to use this library on iOS natively? Instead of getting another separate native library, we could reuse this one on our native codes.

micnem commented 4 months ago

I am interested in setting the credentials in React Native using this library and retrieving them on the native level using SecItemCopyMatching. Can anyone help with this?

micnem commented 4 months ago

I am interested in setting the credentials in React Native using this library and retrieving them on the native level using SecItemCopyMatching. Can anyone help with this?

In answer to my own question, I implemented it this way, where service is equal to the tag you assigned when calling setGenericPassword



  let service = "ACCESS_TOKEN"

  let query: [String: Any] = [
      kSecClass as String: kSecClassGenericPassword,
      kSecAttrService as String: service,
      kSecReturnAttributes as String: kCFBooleanTrue!,
      kSecReturnData as String: kCFBooleanTrue!,
      kSecMatchLimit as String: kSecMatchLimitOne,
  ]

  var item: CFTypeRef?
  let status = SecItemCopyMatching(query as CFDictionary, &item)

  guard status != errSecItemNotFound else {
    print("Error", "Can't find key")
    return ""
  }

  guard status == errSecSuccess else {
      let error = NSError(domain: NSOSStatusErrorDomain, code: Int(status), userInfo: nil)
      print("Error", "Could not read keychain item", error)
      return ""
  }

  guard let existingItem = item as? [String: Any],
        let passwordData = existingItem[kSecValueData as String] as? Data,
        let password = String(data: passwordData, encoding: String.Encoding.utf8),
        let account = existingItem[kSecAttrAccount as String] as? String else {
      print("Error", "Unexpected keychain data")
      return ""
  }

  return password
}