carrythroughcovid / ctc-app

React Native app for CTC
0 stars 0 forks source link

Accessing phone contacts to implement a "friends" feature #17

Open peroh opened 4 years ago

peroh commented 4 years ago

Suggestions

image

Contacts API

Contacts.getPermissionsAsync()

When permission hasn't been granted yet, revoked, or denied:

{
  "canAskAgain": true,
  "expires": "never",
  "granted": false,
  "status": "denied",
}

When permission has been granted:

{
  "canAskAgain": true,
  "expires": "never",
  "granted": true,
  "status": "granted",
}

Contacts.requestPermissionsAsync()

If granted is false, this popup will be triggered every time it is called:

image

If granted is true, the popup won't appear anymore until the permissions are revoked.

Code snippets

Checking for permissions and then requesting permissions:

const { granted } = await Contacts.getPermissionsAsync();
if (granted) {
  doWorkOnContactList()
} else if (!granted && shouldAskForPermission) {
  // shouldAskForPermission will depend on business logic
  const { granted } = await Contacts.requestPermissionsAsync();
  if (granted) {
    doWorkOnContactList()
  }
}

Contacts data structure:

const { data } = await Contacts.getContactsAsync({
  fields: [Contacts.Fields.PhoneNumbers],
});
console.log("Number of contacts:", data.length);
for (var i = 0; i < Math.min(data.length, 100); i++) {
  if (data[i] && data[i].name && data[i].phoneNumbers) {
    console.log(`${data[i].name}: ${data[i].phoneNumbers[0].number}`);
  }
}

Comments

shadforth commented 4 years ago

Great write-up @peroh! 👏

A few thoughts:

peroh commented 4 years ago

Thanks @shadforth