Accessing iOS Address Book with Swift: array count of zero

前端 未结 9 715
陌清茗
陌清茗 2020-12-02 13:05

I am trying to write a simple method to ask a user for access to their address book and then print out the name of each person in the address book. I\'ve seen a number of tu

9条回答
  •  余生分开走
    2020-12-02 13:57

    Other answers provided here were useful, and guided this answer, but had errors and/or were not updated for Swift 3. The following class provides a number of simplifications and safety improvements.

    Usage is simply to call AddressBookService.getContactNames

    There are good reasons to still need to use the ABAddressBook framework, as CNContact does not provide some key data, including creation and modification dates for instance. The deprecated method warnings are somewhat distracting when working with the code, so this code suppresses the warnings that the ABAddressBook methods were deprecated from iOS 9 onwards, instead providing just a single warning to this effect wherever you call the class below.

    //
    //  AddressBookService.swift
    //
    
    import AddressBook
    
    @available(iOS, deprecated: 9.0)
    class AddressBookService: NSObject {
    
        class func getContactNames() {
            let authorizationStatus = ABAddressBookGetAuthorizationStatus()
    
            switch authorizationStatus {
            case .authorized:
                retrieveContactNames()
                break
    
            case .notDetermined:
                print("Requesting Address Book access...")
                let addressBook = AddressBookService.addressBook
                ABAddressBookRequestAccessWithCompletion(addressBook, {success, error in
                    if success {
                        print("Address book access granted")
                        retrieveContactNames()
                    }
                    else {
                        print("Unable to obtain Address Book access.")
                    }
                })
                break
    
            case .restricted, .denied:
                print("Address book access denied")
                break
            }
        }
    
        private class func retrieveContactNames() {
            let addressBook = ABAddressBookCreate().takeRetainedValue()
            let contactList = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray as [ABRecord]
    
            for (index, record) in contactList.enumerated() {
                if let contactName = ABRecordCopyCompositeName(record)?.takeRetainedValue() as String? {
                    print("Contact \(index): \(contactName))")
                }
            }
        }
    }
    

提交回复
热议问题