2015-11-08 19 views
0

我已经编写了以下代码,用于在iOS9中获取与CNContact模块的用户联系人。 iOS8的等效代码是什么,因为我意识到联系人模块是iOS9的新增功能在iOS中获取用户的联系人数组8

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(), ^{ 

     }); 
     return; 
    } 

    // build array of contacts 
    NSMutableArray *contacts = [NSMutableArray array]; 

    NSError *fetchError; 
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, CNContactPhoneNumbersKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]]; 

    BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) { 
     [contacts addObject:contact]; 
    }]; 
    if (!success) { 
     NSLog(@"error = %@", fetchError); 
    } 

    //save array of fetched contacts 
    self.contacts = contacts; 

}]; 

谢谢!

回答

相关问题