我如何将所有联系人电话号码放入数组中



我如何将所有联系人电话号码纳入数组?我需要这个,以将数组发送到我的服务器/db进行检查,如果数据库中存在一个或多个数字。

我仍然与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)
})

您可以使用联系人框架尝试执行此操作。

在访问此信息之前,您需要要求用户的权限。

相关内容

最新更新