react-native-keychain icon indicating copy to clipboard operation
react-native-keychain copied to clipboard

Using it together with native iOS project

Open CyberMew opened this issue 1 year ago • 2 comments

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.

CyberMew avatar Jan 04 '24 23:01 CyberMew

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 avatar Jan 31 '24 16:01 micnem

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
}

micnem avatar Feb 01 '24 13:02 micnem