获取手机中的联系人列表,需要用到系统给我们提供的框架:AddressBook.framework,
1.导入框架;
2.简历模型和管理者:
模型:
.h
#import <Foundation/Foundation.h> @interface Contact : NSObject @property (nonatomic, strong) NSString *name; @property (nonatomic, strong) NSString *phone; +(instancetype)contactWithItem:(id)item; - (instancetype)initWithItem:(id)item; @end
.m
#import "Contact.h" #import <AddressBook/AddressBook.h> @implementation Contact +(instancetype)contactWithItem:(id)item{ return [[Contact alloc] initWithItem:item]; } -(instancetype)initWithItem:(id)item{ self = [super init]; if (self) { NSString *temFirstName = (__bridge NSString *)ABRecordCopyValue((__bridge ABRecordRef)(item), kABPersonFirstNameProperty); NSString *temLastName = (__bridge NSString *)ABRecordCopyValue((__bridge ABRecordRef)(item), kABPersonLastNameProperty); ABMultiValueRef tempPhones = ABRecordCopyValue((__bridge ABRecordRef)(item), kABPersonPhoneProperty); self.name = [NSString stringWithFormat:@"%@%@", temLastName?temFirstName:@"", temFirstName?temLastName:@""]; self.phone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(tempPhones, 0); } return self; } @end
管理者:
.h
#import <Foundation/Foundation.h> @interface ContactManger : NSObject -(instancetype)initWithArray:(NSArray *)contacts; - (NSDictionary *)contactsWithGroup; @end
.m
#import "ContactManger.h" #import "Contact.h" @interface ContactManger () @property (nonatomic, strong) NSArray *myContacts; @property (nonatomic, strong) NSMutableDictionary *contactsDic; @end @implementation ContactManger +(NSString *)phonetic:(NSString *)sourceString{ NSMutableString *source = [sourceString mutableCopy]; CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO); CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO); return source; } -(instancetype)initWithArray:(NSArray *)contacts{ self = [super init]; if (self) { _myContacts = contacts; } return self; } -(NSDictionary *)contactsWithGroup{ for (id item in _myContacts) { Contact *people = [Contact contactWithItem:item]; if (![people.name isEqualToString:@""]) { NSString *nameEnglish = [ContactManger phonetic:people.name]; nameEnglish = [nameEnglish capitalizedString]; unichar k = [nameEnglish characterAtIndex:0]; if (!(k >= ‘A‘ && k <= ‘Z‘)) { k = ‘#‘; } NSString *key = [NSString stringWithFormat:@"%c", k]; NSMutableArray *arrayGroupK = [self.contactsDic objectForKey:key]; if (!arrayGroupK) { arrayGroupK = [[NSMutableArray alloc]initWithCapacity:5]; [arrayGroupK addObject:people]; if (nil == self.contactsDic) { self.contactsDic = [[NSMutableDictionary alloc]initWithCapacity:5]; } [self.contactsDic setObject:arrayGroupK forKey:key]; }else{ [arrayGroupK addObject:people]; } } } return self.contactsDic; } @end
接下来在Vc里面的代码实现如下:
#import "RootViewController.h" #import "MBProgressHUD.h" #import <AddressBook/AddressBook.h> #import "Contact.h" #import "ContactManger.h" #import "LzwTableViewCell.h" @interface RootViewController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate> @property (nonatomic, strong) UITableView *tableView; @property (nonatomic, assign) ABAddressBookRef addressBook; @property (nonatomic, strong) ContactManger *contactManager; @property (nonatomic, strong) NSDictionary *contactsDic; @property (nonatomic, copy) NSArray *keys; @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self creatTableView]; } #pragma mark -- 创建表格 - (void)creatTableView{ self.tableView = ({ UITableView *tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStylePlain]; tableView.delegate =self; tableView.dataSource = self; tableView.backgroundColor = [UIColor lightGrayColor]; [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone]; [self.view addSubview:tableView]; tableView; }); //注册cell [self.tableView registerClass:[LzwTableViewCell class] forCellReuseIdentifier:@"cell"]; [MBProgressHUD showHUDAddedTo:self.view animated:YES]; //检查授权状态 [self checkAddressBookAuthorizationStatus]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [self.keys count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSString *key = [self.keys objectAtIndex:section]; NSArray * array = [self.contactsDic objectForKey:key]; return [array count]; } - (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return self.keys[section]; } - (NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView { return self.keys; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ LzwTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; NSString *key = [self.keys objectAtIndex:indexPath.section]; Contact *people = [[self.contactsDic objectForKey:key] objectAtIndex:indexPath.row]; cell.labelName.text = people.name; cell.labelNumber.text = people.phone; return cell; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 60; } /** * 通讯录的授权状态 */ - (void)checkAddressBookAuthorizationStatus{ //初始化 self.addressBook = ABAddressBookCreateWithOptions(nil, nil); if (kABAuthorizationStatusAuthorized == ABAddressBookGetAuthorizationStatus()) { NSLog(@"已经授权"); } ABAddressBookRequestAccessWithCompletion(self.addressBook, ^(bool granted, CFErrorRef error) { dispatch_async(dispatch_get_main_queue(), ^{ if (error) { [MBProgressHUD hideHUDForView:self.view animated:YES]; NSLog(@"Error: %@", error); }else if (!granted){ [MBProgressHUD hideHUDForView:self.view animated:YES]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authorization Denied" message:@"Set permissions in Setting>Genearl>Privacy." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; }else{ //还原 ABAddressBookRef ABAddressBookRevert(self.addressBook); self.contactManager = [[ContactManger alloc] initWithArray:(__bridge NSArray *)(ABAddressBookCopyArrayOfAllPeople(self.addressBook))]; self.contactsDic = [self.contactManager contactsWithGroup]; self.keys = [[self.contactsDic allKeys] sortedArrayUsingSelector:@selector(compare:)]; [MBProgressHUD hideHUDForView:self.view animated:YES]; [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine]; [self.tableView reloadData]; } }); }); } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSString *key = [self.keys objectAtIndex:indexPath.section]; Contact *people = [[self.contactsDic objectForKey:key] objectAtIndex:indexPath.row]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:people.name message:people.phone delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"打电话", nil]; [alert show]; } #pragma mark - UIAlertViewDelegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { UIApplication *app = [UIApplication sharedApplication]; if (buttonIndex == 1) { [app openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", alertView.message]]]; } } @end
这样就可以实现获取本地通讯录的联系人和打电话功能,效果图如下:
完成!!!
时间: 2024-11-10 11:56:51