如果多个联系人在iOS Swift中获取,则会卡住视图

时间:2019-06-18 10:18:47

标签: ios swift

我有18,000个联系人,并使用Swifty Contact加载所有联系人。但是,当某个应用程序允许联系人访问权限时,整个应用程序将在9-10分钟内无法正常工作。

3 个答案:

答案 0 :(得分:1)

我创建了一个函数来提取所有联系人。看看是否有帮助

导入

import Contacts

ContactModel

 class ContactModel: Codable, Equatable, Hashable{
        var hashValue: Int{
            return phoneNumber.hashValue ^ name.hashValue &* 16777619
        }
        static func ==(lhs: ContactModel, rhs: ContactModel) -> Bool {
            return lhs.phoneNumber == rhs.phoneNumber
        }

        var name: String
        var phoneNumber: String


        init(name: String, phoneNumber: String) {
            self.name = name
            self.phoneNumber = phoneNumber
        }
    }

功能

func fetchContacts(completion: @escaping (_ result: Set<ContactModel>) -> Void){
    DispatchQueue.main.async {
        var results = Set<ContactModel>()
        let keys = [CNContactGivenNameKey,CNContactFamilyNameKey,CNContactMiddleNameKey,CNContactEmailAddressesKey,CNContactPhoneNumbersKey] as [CNKeyDescriptor]
        let fetchRequest = CNContactFetchRequest(keysToFetch: keys)
        fetchRequest.sortOrder = .userDefault
        let store = CNContactStore()
        store.requestAccess(for: .contacts, completionHandler: {(grant,error) in
            if grant{
                do {
                    try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
                        for phone in contact.phoneNumbers{
                            let digits = phone.value.value(forKey: "digits") as! String
                            let model = ContactModel(name: contact.givenName + " " + contact.familyName, phoneNumber: digits)
                            results.insert(model)
                        }
                    })
                }
                catch let error {
                    print(error.localizedDescription)
                }
                DispatchQueue.main.async {
                    completion(results)
                }
            }else {
                print(error?.localizedDescription ?? "")
            }
        })
    }
}

答案 1 :(得分:0)

将联系人加载到后台线程中

DispatchQueue.global(qos: .background).async {
  //write your code
}

答案 2 :(得分:0)

文档中介绍了一种方法,该方法使您可以在后台队列上执行提取。这应该有助于UI卡住

fetchContactsOnBackgroundThread(completionHandler: { (result) in
    switch result{
        case .Success(response: let contacts):
            // Do your thing here with [CNContacts] array    
            break
        case .Error(error: let error):
            print(error)
            break
    }
})