我正在使用CNContacts在我的 iOS 设备中获取电话簿联系人。
当我的手机中有少量联系人(比如 50 个)时,很容易获取联系人。
但是,当我有很多联系人(比如 500-700)时,它会挂起/等待很长时间才能将这些联系人从 iOS 电话簿中提取到我的应用程序数组中。
以前我使用https://github.com/Alterplay/APAddressBook,它是以前 Apple 框架的快速库,但现在我使用的是最新的 Apple 框架。
我获取联系人的代码是....
#pragma mark - Get All Contacts....
-(void)getAllContactsWithNewFrameworkOfApple {
NSMutableArray *_contactsArray = [[NSMutableArray alloc]init];
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusDenied) {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
// [self presentViewController:alert animated:TRUE completion:nil];
return;
}
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
// make sure the user granted us access
if (!granted) {
dispatch_async(dispatch_get_main_queue(), ^{
// user didn't grant access;
// so, again, tell user here why app needs permissions in order to do it's job;
// this is dispatched to the main queue because this request could be running on background thread
});
return;
}
NSError *fetchError;
CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey,CNContactGivenNameKey,CNContactFamilyNameKey,CNContactEmailAddressesKey,CNContactPhoneNumbersKey]];
BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
[_contactsArray addObject:contact];
NSLog(@"I am %@", _contactsArray);
}];
if (!success) {
NSLog(@"error = %@", fetchError);
}else {
NSLog(@"End with Success %@", _contactsArray);
[self finalUsage:_contactsArray];
}
}];
}
我试图分批获取 20 个联系人,每次都重新加载表格。但是在这里它不能在调度线程中重新加载,或者只是崩溃。
如何改进此代码以快速获取联系人?
谢谢。