Search code examples
iosobjective-ccontactscncontact

Issue about the newest Contacts ios Framework


I'm working on my app and at a certain point the user can convince their friends to download it. However, the ABAddressBook framework (link) has been deprecated with iOS 9, so I had to teach myself the newest Contacts framework (link).

However, I'm still facing issues. I have read the documentation up to this point:

NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];

    NSString *containerId = [self.CN_contacts defaultContainerIdentifier];

    NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];

    self.allContacts = [self.CN_contacts unifiedContactsMatchingPredicate:predicate keysToFetch:keysToFetch error:nil];

But I know that the block of code is missing the functionality of asking the user to grant access to their contacts.

Does anyone knows a way to ask user with CNAuthorizationStatus?


Solution

  • You have to use it like this

    switch CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
            {
                case CNAuthorizationStatus.Denied,CNAuthorizationStatus.Restricted :
                 //Handle denied and restricted case
                 break
                case CNAuthorizationStatus.NotDetermined :
                 //Request Access
                contactsStore?.requestAccessForEntityType(CNEntityType.Contacts, completionHandler: { (granted, error) -> Void in
                    //At this point an alert is provided to the user to provide access to contacts. 
                    //This will get invoked if a user responds to the alert
                    if  (!granted ){
                        //User has allowed the access in the alertview provided
                    }
                    else{
                        //User has decline the access in the alertview provided
                    }
                })
                 break
                case  CNAuthorizationStatus.Authorized :
                 //Do your stuff
    
                 NSArray *keysToFetch = @[CNContactGivenNameKey,CNContactFamilyNameKey, CNContactPhoneNumbersKey];
                 NSString *containerId = [self.CN_contacts defaultContainerIdentifier];
                 NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
                 self.allContacts = [self.CN_contacts unifiedContactsMatchingPredicate:predicate keysToFetch:keysToFetch error:nil];
    
                 break
            }