How to fetch only mobile numbers in swift using CNContacts?

随声附和 提交于 2019-12-06 00:37:45

问题


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]()
    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 contacts are stored on an iPhone with a "mobile" label, I was wondering if only these numbers could be added to the array. Thanks :)


回答1:


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 {
        mobiles.append(numVal)
    }
}

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




回答2:


A better way of doing it is mentioned in this post where you use flatMap and contains. Swift nested filter optimization?




回答3:


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
            }
         }

  }


来源:https://stackoverflow.com/questions/37039103/how-to-fetch-only-mobile-numbers-in-swift-using-cncontacts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!