Most part of AddressBook framework is deprecated in iOS 9. In the new Contacts Framework documentation only shows how to fetch records matches a NSPredicate, bu
SWIFT 2
Fetch Full Name, Email Id, Phone Number, Profile Picture from Contacts Framework in iOS9
NOTE Contacts without name has also been handled.
Step 1
import Contacts
Step 2
func fetchContacts(completion: (result: NSMutableArray) -> Void )
{
let finalArrayForContacts = NSMutableArray()
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"
}
var imageData = NSData?()
if contactNew.thumbnailImageData != nil{
imageData = contactNew.thumbnailImageData!
}else{
// imageData = nil
}
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 {
var test = false
if phoneNumber.hasPrefix("+")
{
test = true
}
var resultString : String = (phoneNumber.componentsSeparatedByCharactersInSet(characterSet) as NSArray).componentsJoinedByString("")
if test == true
{
resultString = "+\(resultString)"
}
newDict.setValue(resultString, forKey: "contact_phone")
newDict.setValue(stringFromContact, forKey: "contact_name")
newDict.setValue("0", forKey: "contact_select")
newDict.setValue(imageData, forKey: "contact_image")
finalArrayForContacts.addObject(newDict)
}
}
}else{
// no number saved
}
}
}else {
print("No Contacts Found")
}
completion(result: finalArrayForContacts)
}