How to fetch all contacts record in iOS 9 using Contacts Framework

前端 未结 20 1622
[愿得一人]
[愿得一人] 2020-11-28 01:52

Most part of AddressBook framework is deprecated in iOS 9. In the new Contacts Framework documentation only shows how to fetch records matches a NSPredicate, bu

20条回答
  •  庸人自扰
    2020-11-28 02:14

    Using Swift and Contacts framework to fetch all contacts, including name and phone numbers

    import Contacts
    
    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)")
        }
    
        NSLog(">>>> Contact list:")
        for contact in cnContacts {
            let fullName = CNContactFormatter.stringFromContact(contact, style: .FullName) ?? "No Name"
            NSLog("\(fullName): \(contact.phoneNumbers.description)")
        }
    })
    

    Fetching contact is slow operation, so you should not block main UI thread. Do CNContactFetchRequest on background thread. That's why I put the code into completionHandler. It's run on a background thread.

提交回复
热议问题