2015-11-08 48 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; 

}]; 

謝謝!

回答

相關問題