同事的代码。。。
#import "MyAddressBookVC.h"
#import <MessageUI/MessageUI.h>
#import "PhoneModel.h"
#import <AddressBook/AddressBook.h>
#import "MyAddressBookCell.h"
@interface MyAddressBookVC ()<UITableViewDataSource, UITableViewDelegate, MFMessageComposeViewControllerDelegate, MyAddressBookCellDelegate>{
UITableView *myBookTB;
NSMutableArray *indexArray; // 索引
NSMutableArray *tel_array; //排好序的model 放到这里
PhoneModel *currentModel;
}
@end
@implementation MyAddressBookVC
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"联系人";
indexArray = [[NSMutableArray alloc] init];
tel_array = [[NSMutableArray alloc] init];
[self getAddressBookClick];
[self createUITabelView];
}
#pragma mark - 创建UITabelView
-(void)createUITabelView{
myBookTB = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - navigationHeight) style:UITableViewStylePlain];
myBookTB.showsHorizontalScrollIndicator = NO;
myBookTB.showsVerticalScrollIndicator = NO;
myBookTB.delegate = self;
myBookTB.dataSource = self;
//改变索引的背景颜色
myBookTB.sectionIndexBackgroundColor=[UIColor clearColor];
//改变索引的颜色
myBookTB.sectionIndexColor = [UIColor grayColor];
myBookTB.separatorStyle = UITableViewCellSeparatorStyleNone;
myBookTB.backgroundColor = [UIColor groupTableViewBackgroundColor];
[self.view addSubview:myBookTB];
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return indexArray;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return index;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
if (tel_array.count == 0) {
return 0;
}
return tel_array.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 20;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [MyAddressBookCell getHeight];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[tel_array objectAtIndex:section] count];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UILabel *englishLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.view.frame.size.width - 10, 20)];
englishLabel.text = [NSString stringWithFormat:@" %@",
[indexArray objectAtIndex:section]];
englishLabel.textColor = [UIColor grayColor];
englishLabel.backgroundColor = [UIColor groupTableViewBackgroundColor];
englishLabel.font = [UIFont systemFontOfSize:13.0f];
return englishLabel;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *celD = @"cell";
MyAddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:celD];
if (cell == nil) {
cell = [[MyAddressBookCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celD];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.delegate = self;
PhoneModel *model = [[tel_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
[cell config:model];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
PhoneModel *model = [[tel_array objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
NSLog(@"%@==========%@",model.name,model.phoneTEL);
}
#pragma mark - 添加
-(void)myAddressBookCellDelegateClick:(PhoneModel *)model{
if (model.is_friends || model.is_invite) {
return;
}
currentModel = model;
[self showMessageView:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@",model.phoneTEL], nil] title:@"加班管家" body:[NSString stringWithFormat:@"%@ 一起答题拿红包!",_model.url]];
}
#pragma mark - 短信发送
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
[self dismissViewControllerAnimated:YES completion:nil];
switch (result) {
case MessageComposeResultSent:
//信息传送成功
currentModel.is_invite = YES;
[myBookTB reloadData];
break;
case MessageComposeResultFailed:
//信息传送失败
break;
case MessageComposeResultCancelled:
//信息被用户取消传送
break;
default:
break;
}
}
-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body
{
if( [MFMessageComposeViewController canSendText] )
{
MFMessageComposeViewController * controller = [[MFMessageComposeViewController alloc] init];
controller.recipients = phones;
controller.navigationBar.tintColor = [UIColor redColor];
controller.body = body;
controller.messageComposeDelegate = self;
[[[[controller viewControllers] lastObject] navigationItem] setTitle:title];//修改短信界面标题
[self presentViewController:controller animated:YES completion:nil];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息"
message:@"该设备不支持短信功能"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil, nil];
[alert show];
}
}
#pragma mark - 获取通讯录
- (void)getAddressBookClick{
ABAddressBookRef addressBook = ABAddressBookCreate();
//用户授权
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {//首次访问通讯录
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
if (!error) {
if (granted) {//允许
NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
dispatch_async(dispatch_get_main_queue(), ^{
tel_array = [self userSorting:[NSMutableArray arrayWithArray:contacts]];
[myBookTB reloadData];
});
}else{//拒绝
NSLog(@"拒绝");
}
}else{
NSLog(@"错误!");
}
});
}else{//非首次访问通讯录
NSArray *contacts = [self fetchContactWithAddressBook:addressBook];
dispatch_async(dispatch_get_main_queue(), ^{
tel_array = [self userSorting:[NSMutableArray arrayWithArray:contacts]];
[myBookTB reloadData];
});
}
}
- (NSMutableArray *)fetchContactWithAddressBook:(ABAddressBookRef)addressBook{
if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {有权限访问
//获取联系人数组
NSArray *array = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *contacts = [NSMutableArray array];
for (int i = 0; i < array.count; i++) {
PhoneModel *model = [[PhoneModel alloc] init];
//获取联系人
ABRecordRef people = CFArrayGetValueAtIndex((__bridge ABRecordRef)array, i);
//获取联系人详细信息,如:姓名,电话,住址等信息
NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
ABMutableMultiValueRef phoneNumRef = ABRecordCopyValue(people, kABPersonPhoneProperty);
NSString *phoneNumber = ((__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneNumRef)).lastObject;
//判断手机号null
if (phoneNumber != nil) {
NSString *phone = [phoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];;
model.phoneTEL = [phone stringByReplacingOccurrencesOfString:@" " withString:@""];
}else{
model.phoneTEL = @"";
continue;
}
//判断姓名null
if (firstName == nil && lastName != nil) {
model.name = [NSString stringWithFormat:@"%@",lastName];
}else if (firstName != nil && lastName == nil){
model.name = [NSString stringWithFormat:@"%@",firstName];
}else if (lastName != nil && firstName != nil){
model.name = [NSString stringWithFormat:@"%@%@",lastName,firstName];
}else{
model.name = model.phoneTEL;
}
if ([model.name isEqualToString:@""]) {
model.name = model.phoneTEL;
}
NSPredicate *pre = [NSPredicate predicateWithFormat:@"mobilephone LIKE %@", model.phoneTEL];
NSArray *phoneArr = [_friendArray filteredArrayUsingPredicate:pre];
if (phoneArr.count == 0) {
model.is_friends = NO;
}else{
model.is_friends = YES;
}
//如果不加上面的判断,这里加入数组的时候会出错,不会判断(null)这个东西,所以要先排除
model.firstLetter = [self firstChar:model.name];
model.is_invite = NO;
[contacts addObject:model];
}
return contacts;
}else{//无权限访问
//提示授权
UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录\n设置-隐私-通讯录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alart show];
return nil;
}
}
-(NSString *)firstChar:(NSString *)name{
NSMutableString *mutableString = [NSMutableString stringWithString:name];
// 转拼音
CFStringTransform((__bridge CFMutableStringRef)mutableString, nil, kCFStringTransformToLatin, NO);
// 去掉音标
CFStringTransform((__bridge CFMutableStringRef)mutableString, nil, kCFStringTransformStripDiacritics, NO);
NSString *bigStr = [mutableString uppercaseString]; // bigStr 是转换成功后的拼音
NSString *cha = [bigStr firstChar];
return cha;
}
-(NSMutableArray *)userSorting:(NSMutableArray *)modelArr{
NSMutableArray *array = [[NSMutableArray alloc] init];
for(int i='A';i<='Z';i++)
{
NSMutableArray *rulesArray = [[NSMutableArray alloc] init];
NSString *str1=[NSString stringWithFormat:@"%c",i];
for(int j=0;j<modelArr.count;j++)
{
PhoneModel *model = [modelArr objectAtIndex:j]; //这个model 是我自己创建的 里面包含用户的姓名 手机号 和 转化成功后的首字母
if([model.firstLetter isEqualToString:str1])
{
[rulesArray addObject:model]; //把首字母相同的人物model 放到同一个数组里面
[modelArr removeObject:model]; //model 放到 rulesArray 里面说明这个model 已经拍好序了 所以从总的modelArr里面删除
j--;
}else{
}
}
if (rulesArray.count !=0) {
[array addObject:rulesArray];
[indexArray addObject:[NSString stringWithFormat:@"%c",i]]; //把大写字母也放到一个数组里面
}
}
if (modelArr.count !=0) {
[array addObject:modelArr];
[indexArray addObject:@"#"]; //把首字母不是A~Z里的字符全部放到 array里面 然后返回
}
return array;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end