应用程序访问地址簿时冻结应用程序

时间:2016-12-23 23:46:15

标签: swift abaddressbook cncontact abaddressbooksource

func getContacts() {
    let store = CNContactStore()

    if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined {
        store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: NSError?) -> Void in
            if authorized {
                self.retrieveContactsWithStore(store: store)
            }
        } as! (Bool, Error?) -> Void)
    } else if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
        self.retrieveContactsWithStore(store: store)
    }
}

func retrieveContactsWithStore(store: CNContactStore) {
    do {
        let groups = try store.groups(matching: nil)
        let predicate = CNContact.predicateForContactsInGroup(withIdentifier: groups[0].identifier)
        //let predicate = CNContact.predicateForContactsMatchingName("John")
        let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey] as [Any]

        let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
        self.objects = contacts
        DispatchQueue.main.async(execute: { () -> Void in
            self.myTableView.reloadData()
        })
    } catch {
        print(error)
    }
}

我试图从地址簿中检索联系人,但每当我转到调用getContacts()的视图时,应用程序就会冻结。它不会继续下去,但它也没有崩溃。我想知道这里出了什么问题?

1 个答案:

答案 0 :(得分:1)

您对requestAccess的调用代码不正确。完成处理程序的语法无效。你需要这个:

func getContacts() {
    let store = CNContactStore()

    let status = CNContactStore.authorizationStatus(for: .contacts)
    if status == .notDetermined {
        store.requestAccess(for: .contacts, completionHandler: { (authorized: Bool, error: Error?) in
            if authorized {
                self.retrieveContactsWithStore(store: store)
            }
        })
    } else if status == .authorized {
        self.retrieveContactsWithStore(store: store)
    }
}

另请注意使用status变量的更改。与一遍又一遍地调用authorizationStatus相比,这更清晰,更易于阅读。调用一次,然后根据需要反复检查值。