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

前端 未结 20 1611
[愿得一人]
[愿得一人] 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:11

    Cody's response in Swift 3:

    import Contacts
    

    Then within whatever function you're using:

               let store = CNContactStore()
                store.requestAccess(for: .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.present(alert, animated: true, completion: nil)
                        return
                    }
    
                    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]
                    let request = CNContactFetchRequest(keysToFetch: keysToFetch as! [CNKeyDescriptor])
                    var cnContacts = [CNContact]()
    
                    do {
                        try store.enumerateContacts(with: request){
                            (contact, cursor) -> Void in
                            cnContacts.append(contact)
                        }
                    } catch let error {
                        NSLog("Fetch contact error: \(error)")
                    }
    
                    print(">>>> Contact list:")
                    for contact in cnContacts {
                        let fullName = CNContactFormatter.string(from: contact, style: .fullName) ?? "No Name"
                        print("\(fullName): \(contact.phoneNumbers.description)")
                    }
                })
    

提交回复
热议问题