如何使用CNContacts在swift中仅获取手机号码? [英] How to fetch only mobile numbers in swift using CNContacts?
本文介绍了如何使用CNContacts在swift中仅获取手机号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些代码可以检索用户联系人中的所有电话号码,但我们只想过滤掉手机号码。目前,我只是将数字的第一个数字+或第二个数字7添加到数组中,如下所示:
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)")
}
}
}
}
由于联系人存储在带有移动标签的iPhone上,我是想知道是否只能将这些数字添加到数组中。谢谢:)
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 {
mobiles.append(numVal)
}
}
然后你有一系列的手机号码。
Then you have an array of mobile phone numbers for that person.
这篇关于如何使用CNContacts在swift中仅获取手机号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文