R_McVities R_McVities - 5 months ago 114
Swift Question

How to fetch only mobile numbers in swift using CNContacts?

I have some code to retrieve all the phone numbers in the users contacts, but would like to filter out only mobile numbers. Currently, I am just doing this by only adding numbers with a first digit of "+" or second digit of "7" to an array, as shown below:

func findContacts () -> [CNContact]{
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactPhoneNumbersKey]
let fetchRequest: CNContactFetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)
var contacts = [CNContact]()
fetchRequest.mutableObjects = false
fetchRequest.unifyResults = true
fetchRequest.sortOrder = .UserDefault

let contactStoreID = CNContactStore().defaultContainerIdentifier()

do {

try CNContactStore( ).enumerateContactsWithFetchRequest(fetchRequest) { (let contact, let stop) -> Void in
if contact.phoneNumbers.count > 0 {
if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) {
for phoneNumber:CNLabeledValue in contact.phoneNumbers {
let number = phoneNumber.value as! CNPhoneNumber
let index = number.stringValue.startIndex.advancedBy(1)
let indexPlus = number.stringValue.startIndex.advancedBy(0)
if number.stringValue[index] == Character(String(7)) || number.stringValue[indexPlus] == Character("+"){

Since contacts are stored on an iPhone with a "mobile" label, I was wondering if only these numbers could be added to the array. Thanks :)


Check if the number's label is mobile like this:

var mobiles = [CNPhoneNumber]()

for num in contact.phoneNumbers {
    let numVal = num.value as! CNPhoneNumber
    if num.label == CNLabelPhoneNumberMobile {

Then you have an array of mobile phone numbers for that person.

P.S. If the label isn't "mobile", then change it to whatever the label is for mobile numbers