ios 选择联系人 发短信 通讯录开发 addressUI

来源:互联网 发布:下载wps软件 编辑:程序博客网 时间:2024/05/20 11:36

同事的代码。。。偷笑


#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 [MyAddressBookCellgetHeight];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [[tel_arrayobjectAtIndex:section] count];

}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    

    

    UILabel *englishLabel = [[UILabelalloc] initWithFrame:CGRectMake(10,0, self.view.frame.size.width -10, 20)];

    englishLabel.text = [NSStringstringWithFormat:@"   %@",

                         [indexArray objectAtIndex:section]];

    englishLabel.textColor = [UIColorgrayColor];

    englishLabel.backgroundColor = [UIColorgroupTableViewBackgroundColor];

    englishLabel.font = [UIFontsystemFontOfSize:13.0f];

    

    return englishLabel;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    

        static NSString *celD =@"cell";

        MyAddressBookCell *cell = [tableView dequeueReusableCellWithIdentifier:celD];

        if (cell == nil) {

            cell = [[MyAddressBookCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:celD];

        }

        cell.selectionStyle =UITableViewCellSelectionStyleNone;

        cell.delegate = self;

    

        PhoneModel *model = [[tel_arrayobjectAtIndex:indexPath.section]objectAtIndex:indexPath.row];

    

        [cell config:model];

    

        return cell;

  

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    

    PhoneModel *model = [[tel_arrayobjectAtIndex: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:[NSArrayarrayWithObjects:[NSStringstringWithFormat:@"%@",model.phoneTEL],nil] title:@"加班管家" body:[NSStringstringWithFormat:@"%@ 一起答题拿红包!",_model.url]];

    

}



#pragma mark - 短信发送

-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result

{

    [selfdismissViewControllerAnimated:YEScompletion:nil];

    switch (result) {

        caseMessageComposeResultSent:

            //信息传送成功

            currentModel.is_invite =YES;

            [myBookTB reloadData];

            break;

        caseMessageComposeResultFailed:

            //信息传送失败

            

            break;

        caseMessageComposeResultCancelled:

            //信息被用户取消传送

            

            break;

        default:

            break;

    }

}


-(void)showMessageView:(NSArray *)phones title:(NSString *)title body:(NSString *)body

{

    if( [MFMessageComposeViewControllercanSendText] )

    {

        MFMessageComposeViewController * controller = [[MFMessageComposeViewControlleralloc] init];

        controller.recipients = phones;

        controller.navigationBar.tintColor = [UIColorredColor];

        controller.body = body;

        controller.messageComposeDelegate = self;

        [[[[controller viewControllers]lastObject] navigationItem]setTitle:title];//修改短信界面标题

        

        [selfpresentViewController:controller animated:YEScompletion:nil];

        

    }

    else

    {

        UIAlertView *alert = [[UIAlertViewalloc] 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 = [selffetchContactWithAddressBook:addressBook];

                    dispatch_async(dispatch_get_main_queue(), ^{

                        

                        tel_array = [selfuserSorting:[NSMutableArrayarrayWithArray: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


原创粉丝点击