如何将我所有的联系人 phone 号码放入数组中?

How can I get all my contacts phone numbers into an array?

如何将我所有的联系人 phone 号码放入一个数组中?我需要这个,将数组发送到我的 Server/DB 以检查数据库中是否存在一个或多个数字。

我仍然使用 Swift 2,以后还会使用 Swift 3。

此代码有效,但我认为它存在更好的版本。

// With help: 
// With help: 

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

您可以尝试使用 Contacts Framework

在访问此信息之前,您需要征得用户的许可。