phonePeopleVC.m 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // phonePeopleVC.m
  3. // LN_School
  4. //
  5. // Created by apple on 2017/4/5.
  6. // Copyright © 2017年 Danson. All rights reserved.
  7. //
  8. #import "phonePeopleVC.h"
  9. #import <Contacts/Contacts.h>
  10. @interface phonePeopleVC ()
  11. {
  12. NSMutableArray * _dataArr;
  13. }
  14. @end
  15. @implementation phonePeopleVC
  16. #pragma mark 通讯录
  17. -(void)viewDidLoad{
  18. [super viewDidLoad];
  19. [self requestAuthorizationForAddressBook];
  20. }
  21. - (void)requestAuthorizationForAddressBook {
  22. CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
  23. if (authorizationStatus == CNAuthorizationStatusNotDetermined) {
  24. CNContactStore *contactStore = [[CNContactStore alloc] init];
  25. [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
  26. if (granted) {
  27. // 获取指定的字段,并不是要获取所有字段,需要指定具体的字段
  28. NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
  29. CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
  30. CNContactStore *contactStore = [[CNContactStore alloc] init];
  31. [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
  32. // NSLog(@"-------------------------------------------------------");
  33. NSString *givenName = contact.givenName;
  34. NSString *familyName = contact.familyName;
  35. // NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
  36. NSArray *phoneNumbers = contact.phoneNumbers;
  37. for (CNLabeledValue *labelValue in phoneNumbers) {
  38. NSString *label = labelValue.label;
  39. CNPhoneNumber *phoneNumber = labelValue.value;
  40. // NSLog(@"label=%@, phone=%@", label, phoneNumber.stringValue);
  41. }
  42. // *stop = YES; // 停止循环,相当于break;
  43. }];
  44. } else {
  45. // NSLog(@"授权失败, error=%@", error);
  46. UIAlertController *alertFind = [UIAlertController alertControllerWithTitle:nil message:@"没有打开通讯录授权(设置-隐私-通讯录-极速驾培)" preferredStyle:UIAlertControllerStyleAlert];
  47. [alertFind addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  48. }]];
  49. [self presentViewController:alertFind animated:true completion:nil];
  50. }
  51. }];
  52. }
  53. }
  54. -(void)didReceiveMemoryWarning{
  55. [super didReceiveMemoryWarning];
  56. }
  57. @end