iOS 는 주소록 을 가 져 오 는 도구 류 에 대한 상세 한 설명 을 패키지 합 니 다.
11610 단어 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 를 추가 합 니 다.가 져 온 주소록 데 이 터 를 저장 하기 위해 두 개의 데이터 모델 파일 을 새로 만 듭 니 다.
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);
}];
}
총결산이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Swift의 패스트 패스Objective-C를 대체하기 위해 만들어졌지만 Xcode는 Objective-C 런타임 라이브러리를 사용하기 때문에 Swift와 함께 C, C++ 및 Objective-C를 컴파일할 수 있습니다. Xcode는 S...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.