欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS實(shí)現(xiàn)封裝一個(gè)獲取通訊錄的工具類詳解

 更新時(shí)間:2017年10月31日 09:32:39   作者:hello老文  
這篇文章主要給大家介紹了關(guān)于iOS如何實(shí)現(xiàn)封裝一個(gè)獲取通訊錄的工具類的相關(guān)資料,這是自己平時(shí)封裝的一個(gè)工具類,使用非常方便,文中給出了詳細(xì)的示例代碼,需要的朋友們可以參考借鑒,下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。

前言

本文給大家介紹了關(guān)于iOS如何封裝一個(gè)獲取通訊錄工具類的相關(guān)內(nèi)容,iOS獲取通訊錄一共有4個(gè)framework: AddressBook, AddressBookUI, Contacts, ContactsUI; 其中 AddressBook 和 AddressBookUI 已經(jīng)被iOS9時(shí) deprecated 了, 而推出了Contacts 和 ContactsUI 取代之. 其中 AddressBookUI 和 ContactsUI 是picker出一個(gè)界面提供選擇一條聯(lián)系人信息并且是不需要手動(dòng)授權(quán), AddressBook 和 Contacts 是獲取全部通訊錄數(shù)據(jù)并且需要手動(dòng)授權(quán).下面來一起看看詳細(xì)的介紹吧。

注意:在iOS10獲取通訊錄權(quán)限需主動(dòng)在info.plist里添加上提示信息. 不然會(huì)崩潰. 在info.plist里添加一對key和value

  • key: Privacy - Contacts Usage Description
  • value: 自由發(fā)揮, 這里隨便寫一句: 是否允許此App訪問你的通訊錄?

ContactsModel

新建兩個(gè)數(shù)據(jù)模型文件來保存獲取的通訊錄數(shù)據(jù)

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) { // 用戶還沒有決定是否授權(quán)你的程序進(jìn)行訪問
  ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
   if (granted) {
    contactModels = [self getAddressBookInfo:addressBook];
   } else {
    [self showErrorAlert];
    if (addressBook) CFRelease(addressBook);
   }
  });
  // 用戶已拒絕 或 iOS設(shè)備上的家長控制或其它一些許可配置阻止程序與通訊錄數(shù)據(jù)庫進(jìn)行交互
 } else if (status == kABAuthorizationStatusDenied || status == kABAuthorizationStatusRestricted) {
  [self showErrorAlert];
  if (addressBook) CFRelease(addressBook);
 } else if (status == kABAuthorizationStatusAuthorized) { // 用戶已授權(quán)
  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) { // 用戶還沒有決定是否授權(quán)你的程序進(jìn)行訪問
  [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
   if (granted) {
    contactModels = [self getContactsInfo:store];
   } else {
    [self showErrorAlert];
   }
  }];
  // 用戶已拒絕 或 iOS設(shè)備上的家長控制或其它一些許可配置阻止程序與通訊錄數(shù)據(jù)庫進(jìn)行交互
 } else if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted) {
  [self showErrorAlert];
 } else if (status == CNAuthorizationStatusAuthorized) { // 用戶已授權(quán)
  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(@"授權(quán)失敗, 請?jiān)试Sapp訪問您的通訊錄, 在手機(jī)的”設(shè)置-隱私-通訊錄“選項(xiàng)中設(shè)置允許");
}

@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);
 }];
}

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

  • iOS音樂播放器實(shí)現(xiàn)代碼完整版

    iOS音樂播放器實(shí)現(xiàn)代碼完整版

    這篇文章主要為大家詳細(xì)介紹了iOS音樂播放器實(shí)現(xiàn)代碼完整版,包括音頻列表、播放器、后臺(tái)播放、鎖屏播放,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • 干貨分享!iOS10 SiriKit QQ適配詳解

    干貨分享!iOS10 SiriKit QQ適配詳解

    干貨分享!主要為大家詳細(xì)介紹了!iOS10 SiriKit QQ適配,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • iOS開發(fā)中的幾個(gè)手勢操作實(shí)例分享

    iOS開發(fā)中的幾個(gè)手勢操作實(shí)例分享

    這篇文章主要介紹了iOS開發(fā)中的幾個(gè)手勢操作實(shí)例分享,編寫代碼為傳統(tǒng)的Objective-C,需要的朋友可以參考下
    2015-09-09
  • iOS組件化開發(fā)實(shí)戰(zhàn)記錄

    iOS組件化開發(fā)實(shí)戰(zhàn)記錄

    這篇文章主要給大家介紹了關(guān)于iOS組件化開發(fā)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • xcode 4 制作靜態(tài)庫圖文詳解

    xcode 4 制作靜態(tài)庫圖文詳解

    我這個(gè)文檔的靜態(tài)庫的開發(fā)是基于Xcode4.2和iOS SDK5.0編寫的。Xcode4跟之前的Xcode3還是有不少的差別的
    2013-06-06
  • Objective-C const常量的優(yōu)雅使用方法

    Objective-C const常量的優(yōu)雅使用方法

    這篇文章主要為大家介紹了Objective-C const常量的優(yōu)雅使用方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • iOS多語言本地化流程的優(yōu)化方案

    iOS多語言本地化流程的優(yōu)化方案

    這篇文章主要給大家介紹了關(guān)于iOS多語言本地化流程的優(yōu)化的相關(guān)資料,多語言本地化是我們大家在開發(fā)中經(jīng)常會(huì)遇到的一個(gè)功能,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面隨著小編來一起看看吧。
    2018-01-01
  • IOS微信搖一搖聲音無法播放的解決辦法

    IOS微信搖一搖聲音無法播放的解決辦法

    這篇文章主要為大家詳細(xì)介紹了IOS微信搖一搖聲音無法播放的解決辦法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-05-05
  • IOS 靜態(tài)方法與動(dòng)態(tài)方法詳解

    IOS 靜態(tài)方法與動(dòng)態(tài)方法詳解

    這篇文章主要介紹了IOS 靜態(tài)方法與動(dòng)態(tài)方法詳解的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • iOS給border設(shè)置漸變色的方法實(shí)例

    iOS給border設(shè)置漸變色的方法實(shí)例

    這篇文章主要給大家介紹了關(guān)于iOS給border設(shè)置漸變色的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評論