Fetch contact with new Contact framework

Posted By : Aditya Kumar Sharma | 06-Jan-2017

Apple has introduced the new framework Contacts. It has replace the function based AddressBook framework. Contacts framework provides object-oriented approach to work with user contact info.

So here we are going to Fetch contacts from the device but with new Contact framework which came in iOS 9. 

 

So follow these simple steps for Fetching contacts.

1. Import Contact framework in the file

         import Contacts
     

 

 

 

2. Then we have to check for authorisation. If user has not allowed then we have get permission from user to fetch the contacts. for checking the authorisation you can use the following method:

 

 

      public func askForContactAccess() -> Dictionary {
        var data = Dictionary()

        let authorizationStatus = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)
        switch authorizationStatus {
        case .Authorized:
            // data = fetchContacts()
			// will fetch the contacts
        case .Denied, .NotDetermined:
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.displayCantAddContactAlert()
            })
            break
        default:
            break
        }
        return data
    }
     

 

 

In this method we checking for authorisation status. If it is not been authorised then we are going to show a pop Up to make user allow for contact fetching.

      
  func displayCantAddContactAlert() {
        let cantAddContactAlert = UIAlertController(title: TextMessages().cannotAddcontactMessage, message: TextMessages().mustGivePermissionMessage, preferredStyle: .Alert)
        cantAddContactAlert.addAction(UIAlertAction(title: TextMessages().changeSettingTitle, style: .Default, handler: { action in self.openSettings()}))
        cantAddContactAlert.addAction(UIAlertAction(title: TextMessages().okAlertTitle, style: .Cancel, handler: nil))
        UIApplication.topViewController()?.presentViewController(cantAddContactAlert, animated: true, completion: nil)
    }
    
    func openSettings() {
        let url = NSURL(string: UIApplicationOpenSettingsURLString)
        UIApplication.sharedApplication().openURL(url!)
    }

 

 

4. Now when user has authorised the app to fetch the contacts. Now we have to fetch all the contacts and have to store them in the array with a key attached to them. Like for saving name we give the key “name” and for phone number we give “number”.


            func fetchContacts() -> Dictionary {
		
		let contactsArray = NSMutableArray()
        let requestForContacts = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName), CNContactPhoneNumbersKey ,CNContactThumbnailImageDataKey])
        do{
            try contactStore.enumerateContactsWithFetchRequest(requestForContacts) { (contactStore : CNContact, stop: UnsafeMutablePointer) -> Void in
                contactsArray.addObject(contactStore)
            }
        }
        catch {}
        if contactsArray.count > 0 {
            let formatter = CNContactFormatter()
            for contactTemp  in contactsArray
            {
                let contactNew = contactTemp as! CNContact
                //Contact Name
                var stringFromContact = formatter.stringFromContact(contactNew)
                if stringFromContact == nil {
                    stringFromContact = "Unnamed"
                }
                //Identifier
                let stringFromIdentifier = contactNew.identifier
                
                var tempArray : NSArray = NSArray()
                if (contactNew.phoneNumbers).count > 0 {
                    tempArray = ((contactNew.phoneNumbers as? NSArray)?.valueForKey("value").valueForKey("digits")) as! NSArray
                    for i in 0  ..< tempArray.count {
                        let newDict = NSMutableDictionary()
                        let phoneNumber : String = (tempArray.objectAtIndex(i)) as! String
                        if phoneNumber.characters.count > 0 {
                            let resultString : String = (phoneNumber.componentsSeparatedByCharactersInSet(NSCharacterSet.symbolCharacterSet()) as NSArray).componentsJoinedByString("")
                            
                            newDict.setValue(stringFromIdentifier, forKey: "recordID")
                            newDict.setValue(resultString, forKey: "phonenumber")
                            newDict.setValue(stringFromContact, forKey: "name")
                            self.contactDetails.append(newDict)
                        }
                    }
                }else{ // no number saved
                }
            }
        }else {
            print("No Contacts Found")
        }
	}
     

 

here we fetched all the contacts with the help of framework and stored them in the ContactDetails array with a key attached to them. Now we can use this array to show the Contacts in our App.

 

Thanks

 

 

 

About Author

Author Image
Aditya Kumar Sharma

Aditya is a bright iOS developer, have knowledge of objective C, swift, swift 3, JSON, Core data and iPhone development. Apart from that he loves to travel and explore new things.

Request for Proposal

Name is required

Comment is required

Sending message..