mahesh kolagatla
mahesh kolagatla

Reputation: 83

How to retrieve emails from iPhone Contacts using swift?

I am new to swift . I used APAdressBook Framework for retrieving contacts in iPhone .Every thing working fine up to IOS 8.4 but when checked in IOS 9 of Simulator and iPhone devices it is not accessing contacts and even it not showing alert message like would you like to access contacts any one can face this type of problem if yes please give me your valuable answer?

Upvotes: 0

Views: 4161

Answers (1)

VRAwesome
VRAwesome

Reputation: 4803

Apple Inc. introduce Contacts.framework from iOS 9. So, it would be better use this framework to retrieve contacts.

Here is way to fetch email or whole contact from Contacts app.

Add Contacts.framework to your project.

Create or add new file of type header and give name like yourProjectName-Bridging-Header.h write #import <Contacts/Contacts.h> statement into file and save and set appropriate path of this file from build setting.

Now create method

func getAllContacts() {

    let status = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts) as CNAuthorizationStatus

    if status == CNAuthorizationStatus.Denied {

        let alert = UIAlertController(title:nil, message:"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts", preferredStyle:UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil))
        self.presentViewController(alert, animated:true, completion:nil)
        return
    }

    let store = CNContactStore()
    store.requestAccessForEntityType(CNEntityType.Contacts) { (granted:Bool, error:NSError?) -> Void in

        if !granted {

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                // user didn't grant access;
                // so, again, tell user here why app needs permissions in order  to do it's job;
                // this is dispatched to the main queue because this request could be running on background thread
            })
            return
        }

        let arrContacts = NSMutableArray() // Declare this array globally, so you can access it in whole class.

        let request = CNContactFetchRequest(keysToFetch:[CNContactIdentifierKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey, CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName)])

        do {

            try store.enumerateContactsWithFetchRequest(request, usingBlock: { (contact:CNContact, stop:UnsafeMutablePointer<ObjCBool>) -> Void in

                let arrEmail = contact.emailAddresses as NSArray

                if arrEmail.count > 0 {

                    let dict = NSMutableDictionary()
                    dict.setValue((contact.givenName+" "+contact.familyName), forKey: "name")
                    let emails = NSMutableArray()

                    for index in 0...arrEmail.count {

                        let email:CNLabeledValue = arrEmail.objectAtIndex(index) as! CNLabeledValue
                        emails .addObject(email.value as! String)
                    }
                    dict.setValue(emails, forKey: "email")
                    arrContacts.addObject(dict) // Either retrieve only those contact who have email and store only name and email
                }
                arrContacts.addObject(contact) // either store all contact with all detail and simplifies later on
            })
        } catch {

            return;
        }
    }
}

Call this method where you want self.getAllContacts()

And when you want to retrieve

for var index = 0; index < self.arrContacts.count; ++index {

            let dict = self.arrContacts[index] as! NSDictionary
            print(dict.valueForKey("name"))
            print(dict.valueForKey("email"))
        }

Upvotes: 4

Related Questions