swiftcncontact

How can I get all my contacts phone numbers into an array?


How can I get all my contacts phone numbers into an array? I need this, to send the array to my Server/DB to check, if one or more numbers exist in the Database.

I still work with Swift 2, later also with Swift 3.

This code works, but I think, it exist a much more better version.

// With help: http://stackoverflow.com/questions/37039103/how-to-fetch-only-mobile-numbers-in-swift-using-cncontacts
// With help: http://stackoverflow.com/questions/32669612/how-to-fetch-all-contacts-record-in-ios-9-using-contacts-framework/34095632

let store = CNContactStore()

store.requestAccessForEntityType(.Contacts, completionHandler: {
    granted, error in

    guard granted else {
        let alert = UIAlertController(title: "Can't access contact", message: "Please go to Settings -> MyApp to enable contact permission", preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
        return
    }

    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName), CNContactPhoneNumbersKey]
    let request = CNContactFetchRequest(keysToFetch: keysToFetch)
    var cnContacts = [CNContact]()

    do {
        try store.enumerateContactsWithFetchRequest(request){
            (contact, cursor) -> Void in
            cnContacts.append(contact)
        }
    } catch let error {
        NSLog("Fetch contact error: \(error)")
    }

    var mobilenumbers: [String] = []

    NSLog(">>>> Contact list:")
    for contact in cnContacts {
        let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "No Name"
        NSLog("\(fullName): \(contact.phoneNumbers.description)")

        // If phoneNo a Mobilenumber, then put into Array:
        for phoneNo in contact.phoneNumbers {
            if phoneNo.label == CNLabelPhoneNumberMobile {
                let istEineMobileNummer = (phoneNo.value as! CNPhoneNumber).stringValue


                    mobilenumbers.append(istEineMobileNummer)
            }
        }
    }

    print("Print all Mobilenumbers:")
    print(mobilenumbers)
})

Solution

  • You can attempt to do this by using the Contacts Framework.

    You'll need to ask for the user's permission before accessing this information.