iOS 는 주소록 을 가 져 오 는 도구 류 에 대한 상세 한 설명 을 패키지 합 니 다.

머리말
본 고 는 iOS 가 주소록 도구 류 를 가 져 오 는 방법 에 관 한 내용 을 소개 했다.iOS 가 주소록 을 가 져 오 는 데 모두 4 개의 framework 가 있다.AddressBook,AddressBookUI,Contacts,Contacts UI;그 중에서 AddressBook 과 AddressBookUI 는 iOS 9 시 deprecated 되 었 고 Contacts 와 ContactsUI 로 대체 되 었 습 니 다.그 중에서 AddressBookUI 와 ContactsUI 는 picker 가 하나의 인터페이스 에서 연락처 정 보 를 선택 하고 수 동 으로 권한 을 부여 하지 않 아 도 됩 니 다.주소록 과 Contacts 는 모든 주소록 데 이 터 를 가 져 오고 수 동 으로 권한 을 부여 해 야 합 니 다.다음은 상세 한 소 개 를 살 펴 보 겠 습 니 다.
메모:iOS 10 에서 주소록 권한 을 가 져 오 려 면info.plist에 알림 정 보 를 주동 적 으로 추가 해 야 합 니 다.그렇지 않 으 면 무 너 집 니 다.info.plist에 key 와 value 를 추가 합 니 다.
  • key: Privacy - Contacts Usage Description
  • value:자 유 롭 게 발휘 합 니 다.여기 마음대로 한 마디 쓰 세 요.이 앱 이 당신 의 주소록 에 접근 할 수 있 도록 허락 하 시 겠 습 니까?
  • ContactsModel
    가 져 온 주소록 데 이 터 를 저장 하기 위해 두 개의 데이터 모델 파일 을 새로 만 듭 니 다.
    ContactsModel.h
    
    #import <Foundation/Foundation.h>
    
    @interface ContactsModel : NSObject
    @property (nonatomic, copy) NSString *num;
    @property (nonatomic, copy) NSString *name;
    
    - (instancetype)initWithName:(NSString *)name num:(NSString *)num;
    @end
    ContactsModel.m
    
    #import "ContactsModel.h"
    
    @implementation ContactsModel
    
    - (instancetype)initWithName:(NSString *)name num:(NSString *)num {
     if (self = [super init]) {
      self.name = name;
      self.num = num;
     }
     return self;
    }
    
    @end
    ContactsHelp
    이것 은 주소록 을 가 져 오 는 도구 클래스 입 니 다.
    ContactsHelp.h
    
    #import <UIKit/UIKit.h>
    #import "ContactsModel.h"
    
    typedef void(^ContactBlock)(ContactsModel *contactsModel);
    
    @interface ContactsHelp : NSObject
    
    + (NSMutableArray *)getAllPhoneInfo;
    
    - (void)getOnePhoneInfoWithUI:(UIViewController *)target callBack:(ContactBlock)block;
    
    @end
    ContactsHelp.m
    
    #import "ContactsHelp.h"
    #import <AddressBook/AddressBook.h>
    #import <AddressBookUI/AddressBookUI.h>
    #import <Contacts/Contacts.h>
    #import <ContactsUI/ContactsUI.h>
    
    #define iOS9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)
    
    @interface ContactsHelp () <CNContactPickerDelegate, ABPeoplePickerNavigationControllerDelegate>
    @property(nonatomic, strong) ContactsModel *contactModel;
    @property(nonatomic, strong) ContactBlock myBlock;
    @end
    
    @implementation ContactsHelp
    
    + (NSMutableArray *)getAllPhoneInfo {
     return iOS9 ? [self getContactsFromContacts] : [self getContactsFromAddressBook];
    }
    
    - (void)getOnePhoneInfoWithUI:(UIViewController *)target callBack:(void (^)(ContactsModel *))block {
     if (iOS9) {
      [self getContactsFromContactUI:target];
     } else {
      [self getContactsFromAddressBookUI:target];
     }
     self.myBlock = block;
    }
    
    #pragma mark - AddressBookUI
    - (void)getContactsFromAddressBookUI:(UIViewController *)target {
     ABPeoplePickerNavigationController *pickerVC = [[ABPeoplePickerNavigationController alloc] init];
     pickerVC.peoplePickerDelegate = self;
     [target presentViewController:pickerVC animated:YES completion:nil];
    }
    
    - (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
     ABMultiValueRef phonesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
     if (!phonesRef) { return; }
     NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phonesRef, 0);
    
     CFStringRef lastNameRef = ABRecordCopyValue(person, kABPersonLastNameProperty);
     CFStringRef firstNameRef = ABRecordCopyValue(person, kABPersonFirstNameProperty);
     NSString *lastname = (__bridge_transfer NSString *)(lastNameRef);
     NSString *firstname = (__bridge_transfer NSString *)(firstNameRef);
     NSString *name = [NSString stringWithFormat:@"%@%@", lastname == NULL ? @"" : lastname, firstname == NULL ? @"" : firstname];
     NSLog(@"  : %@", name);
    
     ContactsModel *model = [[ContactsModel alloc] initWithName:name num:phoneValue];
     NSLog(@"    : %@", phoneValue);
    
     CFRelease(phonesRef);
     if (self.myBlock) self.myBlock(model);
    }
    
    #pragma mark - ContactsUI
    - (void)getContactsFromContactUI:(UIViewController *)target {
     CNContactPickerViewController *pickerVC = [[CNContactPickerViewController alloc] init];
     pickerVC.delegate = self;
     [target presentViewController:pickerVC animated:YES completion:nil];
    }
    
    - (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
     NSString *name = [NSString stringWithFormat:@"%@%@", contact.familyName == NULL ? @"" : contact.familyName, contact.givenName == NULL ? @"" : contact.givenName];
     NSLog(@"  : %@", name);
    
     CNPhoneNumber *phoneNumber = [contact.phoneNumbers[0] value];
     ContactsModel *model = [[ContactsModel alloc] initWithName:name num:[NSString stringWithFormat:@"%@", phoneNumber.stringValue]];
     NSLog(@"    : %@", phoneNumber.stringValue);
    
     if (self.myBlock) self.myBlock(model);
    }
    
    #pragma mark - AddressBook
    + (NSMutableArray *)getContactsFromAddressBook {
     ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
     CFErrorRef myError = NULL;
     ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &myError);
     if (myError) {
      [self showErrorAlert];
      if (addressBook) CFRelease(addressBook);
      return nil;
     }
    
     __block NSMutableArray *contactModels = [NSMutableArray array];
     if (status == kABAuthorizationStatusNotDetermined) { //                    
      ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
       if (granted) {
        contactModels = [self getAddressBookInfo:addressBook];
       } else {
        [self showErrorAlert];
        if (addressBook) CFRelease(addressBook);
       }
      });
      //         iOS                                
     } else if (status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted) {
      [self showErrorAlert];
      if (addressBook) CFRelease(addressBook);
     } else if (status == kABAuthorizationStatusAuthorized) { //      
      contactModels = [self getAddressBookInfo:addressBook];
     }
     return contactModels;
    }
    
    + (NSMutableArray *)getAddressBookInfo:(ABAddressBookRef)addressBook {
     CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
     NSInteger peopleCount = CFArrayGetCount(peopleArray);
     NSMutableArray *contactModels = [NSMutableArray array];
    
     for (int i = 0; i < peopleCount; i++) {
      ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
      ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
      if (phones) {
       NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
       NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
       NSString *name = [NSString stringWithFormat:@"%@%@", lastName == NULL ? @"" : lastName, firstName == NULL ? @"" : firstName];
       NSLog(@"  : %@", name);
    
       CFIndex phoneCount = ABMultiValueGetCount(phones);
       for (int j = 0; j < phoneCount; j++) {
        NSString *phoneValue = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phones, j);
        NSLog(@"    : %@", phoneValue);
        ContactsModel *model = [[ContactsModel alloc] initWithName:name num:phoneValue];
        [contactModels addObject:model];
       }
      }
      CFRelease(phones);
     }
    
     if (addressBook) CFRelease(addressBook);
     if (peopleArray) CFRelease(peopleArray);
    
     return contactModels;
    }
    
    
    #pragma mark - Contacts
    + (NSMutableArray *)getContactsFromContacts {
     CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
     CNContactStore *store = [[CNContactStore alloc] init];
     __block NSMutableArray *contactModels = [NSMutableArray array];
    
     if (status == CNAuthorizationStatusNotDetermined) { //                    
      [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
       if (granted) {
        contactModels = [self getContactsInfo:store];
       } else {
        [self showErrorAlert];
       }
      }];
      //         iOS                                
     } else if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) {
      [self showErrorAlert];
     } else if (status == CNAuthorizationStatusAuthorized) { //      
      contactModels = [self getContactsInfo:store];
     }
    
     return contactModels;
    }
    
    + (NSMutableArray *)getContactsInfo:(CNContactStore *)store {
     NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
     CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
     NSMutableArray *contactModels = [NSMutableArray array];
    
     [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
      NSString *name = [NSString stringWithFormat:@"%@%@", contact.familyName == NULL ? @"" : contact.familyName, contact.givenName == NULL ? @"" : contact.givenName];
      NSLog(@"  : %@", name);
    
      for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
       CNPhoneNumber *phoneNumber = labeledValue.value;
       NSLog(@"    : %@", phoneNumber.stringValue);
       ContactsModel *model = [[ContactsModel alloc] initWithName:name num:phoneNumber.stringValue];
       [contactModels addObject:model];
      }
     }];
    
     return contactModels;
    }
    
    #pragma mark - Error
    + (void)showErrorAlert {
     NSLog(@"    ,    app       ,     ”  -  -   “       ");
    }
    
    @end
    쓰다
    
    #import "ContactsHelp.h"
    #import "ContactsModel.h"
    
    ...
    
    @property(nonatomic, strong) ContactsHelp *contactsHelp;
    
    ...
    
    - (IBAction)btn_getOne {
     self.contactsHelp = [[ContactsHelp alloc] init];
     [self.contactsHelp getOnePhoneInfoWithUI:self callBack:^(ContactsModel *contactModel) {
      NSLog(@"-----------");
      NSLog(@"%@", contactModel.name);
      NSLog(@"%@", contactModel.num);
     }];
    }
    
    - (IBAction)btn_getAll {
     NSMutableArray *contactModels = [ContactsHelp getAllPhoneInfo];
     [contactModels enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
      ContactsModel *model = obj;
      NSLog(@"-----------");
      NSLog(@"%@", model.name);
      NSLog(@"%@", model.num);
     }];
    }
    총결산
    이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.

    좋은 웹페이지 즐겨찾기