How to quickly get only mobile numbers using CNContacts?

I have a code to retrieve all phone numbers in user contacts, but you want to filter only mobile numbers. Currently, I just do this by only adding numbers with the first digit "+" or the second digit "7" to the array, as shown below:

func findContacts () -> [CNContact]{ let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactPhoneNumbersKey] let fetchRequest: CNContactFetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch) var contacts = [CNContact]() CNContact.localizedStringForKey(CNLabelPhoneNumberiPhone) 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 { contacts.append(contact) } if (contact.isKeyAvailable(CNContactPhoneNumbersKey)) { for phoneNumber:CNLabeledValue in contact.phoneNumbers { let number = phoneNumber.value as! CNPhoneNumber print(number.stringValue) 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("+"){ self.allNumbers.append("\(number.stringValue)") } } } } 

Since the contacts are stored on the iPhone with a β€œmobile” tag, I was wondering if only these numbers could be added to the array. Thanks:)

+5
source share
3 answers

Check if the number tag is mobile:

 var mobiles = [CNPhoneNumber]() for num in contact.phoneNumbers { let numVal = num.value as! CNPhoneNumber if num.label == CNLabelPhoneNumberMobile { mobiles.append(numVal) } } 

Then you have a set of mobile phone numbers for this person.

+6
source

The best way to do this is mentioned in this post where you use flatMap and contains . Optimal filtering of nested filters?

0
source

Another method for more visitors:

 for con in contacts { for num in con.phoneNumbers { if num.label == "_$!<Mobile>!$_" { self.contactNames.append(con.givenName) self.contactNums.append(num.value.stringValue) break } else { continue } } } 
0
source

All Articles