如何将所有联系人电话号码放入阵列?我需要这个,将数组发送到我的服务器/数据库以检查数据库中是否存在一个或多个数字。
我仍然使用swift 2,后来还使用swift 3。
此代码有效,但我认为它存在更好的版本。你能救我吗?
感谢您的支持。
// 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)
})