Viber、Telegram、WhatsApp等iOS消息应用程序是如何快速高效地获取联系人的



我不知道这个问题是否符合条件,但即使经过这么多研究,我也找不到适合这个问题的指南。我希望我能在这里得到答案。

我看到所有的消息应用程序,如Viber、WhatsApp、Telegram,都能快速高效地获取用户联系人并进行解析,几乎没有延迟。我试图复制它,但从未成功。通过在后台线程上运行整个操作,解析3000个联系人总是需要40-60秒的时间。即便如此,也会导致UI在5和5S等速度较慢的设备上冻结。在获取联系人后,我必须将其发送到后端,以确定哪个用户在平台上注册,这也会增加总时间。上面提到的应用程序很快就能做到这一点!

如果有人能提出一种在不阻塞主线程的情况下以最高效、更快的方式解析联系人的方法,我会很高兴。

这是我现在使用的代码。

final class CNContactsService: ContactsService {
private let phoneNumberKit = PhoneNumberKit()
private var allContacts:[Contact] = []
private let contactsStore: CNContactStore

init(network:Network) {
contactsStore = CNContactStore()
self.network = network
}
func fetchContacts() {
fetchLocalContacts { (error) in
if let uError = error {
} else {
let contactsArray = self.allContacts
self.checkContacts(contacts: contactsArray, checkCompletion: { (Users) in
let nonUsers = contactsArray.filter { contact in
return !Users.contains(contact)
}
self.Users.value = Users
self.nonUsers.value = nonUsers
})
}
}
}
func fetchLocalContacts(_ completion: @escaping (NSError?) -> Void) {
switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) {
case CNAuthorizationStatus.denied, CNAuthorizationStatus.restricted:
//User has denied the current app to access the contacts.
self.displayNoAccessMsg()
case CNAuthorizationStatus.notDetermined:
//This case means the user is prompted for the first time for allowing contacts
contactsStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (granted, error) -> Void in
//At this point an alert is provided to the user to provide access to contacts. This will get invoked if a user responds to the alert
if  (!granted ){
DispatchQueue.main.async(execute: { () -> Void in
completion(error as! NSError)
})
} else{
self.fetchLocalContacts(completion)
}
})
case CNAuthorizationStatus.authorized:
//Authorization granted by user for this app.
var contactsArray = [EPContact]()
let contactFetchRequest = CNContactFetchRequest(keysToFetch: allowedContactKeys)
do {
//                let phoneNumberKit = PhoneNumberKit()
try self.contactsStore.enumerateContacts(with: contactFetchRequest, usingBlock: { (contact, stop) -> Void in
//Ordering contacts based on alphabets in firstname
if let contactItem = self.contactFrom(contact: contact) {
contactsArray.append(contactItem)
}
})
self.allContacts = contactsArray
completion(nil)
} catch let error as NSError {
print(error.localizedDescription)
completion(error)
}
}
}
private var allowedContactKeys: [CNKeyDescriptor]{
//We have to provide only the keys which we have to access. We should avoid unnecessary keys when fetching the contact. Reducing the keys means faster the access.
return [
CNContactGivenNameKey as CNKeyDescriptor,
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactOrganizationNameKey as CNKeyDescriptor,
CNContactThumbnailImageDataKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor,
]
}
private func checkUsers(contacts:[Contact],checkCompletion:@escaping ([Contact])->Void) {
let phoneNumbers = contacts.flatMap{$0.phoneNumbers}
if phoneNumbers.isEmpty {
checkCompletion([])
return
}
network.request(.registeredContacts(numbers: phoneNumbersList), completion: { (result) in
switch result {
case .success(let response):
do {
let profiles = try response.map([Profile].self)
let contacts = profiles.map{ CNContactsService.contactFrom(profile: $0) }
checkCompletion(contacts)
} catch {
checkCompletion([])
}
case .failure:
checkCompletion([])
}
})
}
static func contactFrom(profile:Profile) -> Contact {
let firstName = ""
let lastName = ""
let company = ""
var displayName = ""
if let fullName = profile.fullName {
displayName = fullName
} else {
displayName = profile.nickName ?? ""
}
let numbers = [profile.phone!]
if displayName.isEmpty {
displayName = profile.phone!
}
let contactId = String(profile.id)
return Contact(firstName: firstName,
lastName: lastName,
company: company,
displayName: displayName,
thumbnailProfileImage: nil,
contactId: contactId,
phoneNumbers: numbers,
profile: profile)
}
private func parsePhoneNumber(_ number: String) -> String? {
do {
let phoneNumber = try phoneNumberKit.parse(number)
return phoneNumberKit.format(phoneNumber, toType: .e164)
} catch {
return nil
}
}

}`

当应用程序启动时,联系人会在这里提取

private func ApplicationLaunched() {
DispatchQueue.global(qos: .background).async {
let contactsService:ContactsService = self.serviceHolder.get()
contactsService.fetchContacts()
}

另一个解决方案是在PhoneNumberKit中实际使用正确的方法:-)

我遇到了和您相同的问题,然后意识到PhoneNumberKit有两种方法,并且我使用了错误的方法:

  • 第一个,用于解析个人电话号码(这是您在上面的代码中使用的电话号码)。它将单个对象作为输入
  • 另一个允许同时解析电话号码数组的方法。它采用一个电话号码数组作为输入

这两种方法的命名令人困惑,因为它们除了输入之外都是相同的,但性能上的差异是惊人的:

  • 使用个人电话号码解析方法(带有for循环和你一样)花了大约60秒
  • 使用数组解析方法解析<2秒

所以,如果有人想使用Swift原生库,我鼓励你使用电话号码工具包,因为它工作得很好,有很多方便的方法(比如自动格式化TextFields)。

我的猜测是,您发送到后端的联系人数量是巨大的。3000联系人太多了,我认为以下情况之一正在发生:

  1. 或者请求太大,并且为后端交付需要时间
  2. 它对后端来说太重了,处理和返回客户端需要时间,这就是导致延迟的原因

最不可能的问题是:

  1. 您的解析方法占用了大量CPU。但这不太可能

您测量了解析开始和结束之间的持续时间吗?

我认为你应该衡量你正在做的所有动作之间的持续时间,例如:

  1. 测量从设备中取出联系人所需的时间
  2. 测量分析联系人所需的时间
  3. 测量从后端获得响应所需的时间

这将帮助您准确定位耗时过长的原因。

我希望这有助于解决你的问题。

最新更新