iOS调用电话本保存联系人信息或者打电话发短信不跳转

//

//  AddressBookHelper.h

//  Chengjiao

//

//  Created by Lin² on 2016/9/5.

//  Copyright © 2016 chengjiao. All rights reserved.

//


#import <Foundation/Foundation.h>


enum {

扫描二维码关注公众号,回复: 1574698 查看本文章

    ABHelperCanNotConncetToAddressBook,

    ABHelperExistSpecificContact,

    ABHelperNotExistSpecificContact

};


typedef NSUInteger ABHelperCheckExistResultType;


@interface AddressBookHelper : NSObject

// 添加联系人

// name     ->联系人姓名

// phoneNum    -> 电话号码

// label    ->电话号码的标签备注

+ (BOOL)addContactName:(NSString*)name phoneNum:(NSString*)num withLabel:(NSString*)label;


// 查询指定号码是否已存在于通讯录

// 返回值:

//  ABHelperCanNotConncetToAddressBook ->连接通讯录失败(iOS6之后访问通讯录需要用户许可)

//  ABHelperExistSpecificContact    ->号码已存在

//  ABHelperNotExistSpecificContact  ->号码不存在

+ (ABHelperCheckExistResultType)existPhone:(NSString*)phoneNum;


@end




//

//  AddressBookHelper.m

//  Chengjiao

//

//  Created by Lin² on 2016/9/5.

//  Copyright © 2016 chengjiao. All rights reserved.

//


#import "AddressBookHelper.h"


#import <AddressBook/AddressBook.h>


@implementation AddressBookHelper


// 单列模式

+ (AddressBookHelper *)shareControl {

    staticAddressBookHelper *instance;

    @synchronized(self) {

        if(!instance) {

            instance = [[AddressBookHelperalloc] init];

        }

    }

    return instance;

}


+ (BOOL)addContactName:(NSString *)name phoneNum:(NSString *)num withLabel:(NSString *)label {

    return [[AddressBookHelpershareControl] addContactName:namephoneNum:num withLabel:label];

}


// 添加联系人(联系人名称、号码、号码备注标签)

- (BOOL)addContactName:(NSString*)name phoneNum:(NSString*)num withLabel:(NSString*)label {

    // 创建一条空的联系人

    ABRecordRef record =ABPersonCreate();

    CFErrorRef error;

    // 设置联系人的名字

    ABRecordSetValue(record,kABPersonFirstNameProperty, (__bridgeCFTypeRef)name, &error);

    // 添加联系人电话号码以及该号码对应的标签名

    ABMutableMultiValueRef multi =ABMultiValueCreateMutable(kABPersonPhoneProperty);

    ABMultiValueAddValueAndLabel(multi, (__bridgeCFTypeRef)num, (__bridgeCFTypeRef)label, NULL);

    ABRecordSetValue(record,kABPersonPhoneProperty, multi, &error);

    

    ABAddressBookRef addressBook =nil;

    // 如果为iOS6以上系统,需要等待用户确认是否允许访问通讯录。

    if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 6.0) {

        addressBook = ABAddressBookCreateWithOptions(NULL,NULL);

        //等待同意后向下执行

        dispatch_semaphore_t sema =dispatch_semaphore_create(0);

        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted,CFErrorRef error)

                                                 {

                                                     dispatch_semaphore_signal(sema);

                                                 });

        dispatch_semaphore_wait(sema,DISPATCH_TIME_FOREVER);

        //        dispatch_release(sema);

    }

    else {

        //        addressBook = ABAddressBookCreate();

        addressBook = ABAddressBookCreateWithOptions(NULL, (CFErrorRef *)&error);

    }

    

    // 将新建联系人记录添加如通讯录中

    BOOL success =ABAddressBookAddRecord(addressBook, record, &error);

    if (!success) {

        returnNO;

    }else{

        

        // 如果添加记录成功,保存更新到通讯录数据库中

        success = ABAddressBookSave(addressBook, &error);

        return success ?YES : NO;

    }

}


+ (ABHelperCheckExistResultType)existPhone:(NSString *)phoneNum {

    return [[AddressBookHelpershareControl] existPhone:phoneNum];

}


// 指定号码是否已经存在

- (ABHelperCheckExistResultType)existPhone:(NSString*)phoneNum {

    ABAddressBookRef addressBook =nil;

    CFErrorRef error;

    if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 6.0) {

        addressBook = ABAddressBookCreateWithOptions(NULL,NULL);

        //等待同意后向下执行

        dispatch_semaphore_t sema =dispatch_semaphore_create(0);

        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted,CFErrorRef error)

                                                 {

                                                     dispatch_semaphore_signal(sema);

                                                 });

        dispatch_semaphore_wait(sema,DISPATCH_TIME_FOREVER);

        //        dispatch_release(sema);

    }else {

        //        addressBook = ABAddressBookCreate();

        addressBook = ABAddressBookCreateWithOptions(NULL, (CFErrorRef *)&error);

    }

    CFArrayRef records;

    if (addressBook) {

        // 获取通讯录中全部联系人

        records = ABAddressBookCopyArrayOfAllPeople(addressBook);

    }else{

#ifdef DEBUG

        MSLog(@"can not connect to address book");

#endif

        returnABHelperCanNotConncetToAddressBook;

    }

    // 遍历全部联系人,检查是否存在指定号码

    for (int i=0; i<CFArrayGetCount(records); i++) {

        ABRecordRef record =CFArrayGetValueAtIndex(records, i);

        CFTypeRef items =ABRecordCopyValue(record,kABPersonPhoneProperty);

        CFArrayRef phoneNums =ABMultiValueCopyArrayOfAllValues(items);

        if (phoneNums) {

            for (int j=0; j<CFArrayGetCount(phoneNums); j++) {

                NSString *phone = (NSString *)CFArrayGetValueAtIndex(phoneNums, j);

                

                NSString *realPhone = [phonestringByReplacingOccurrencesOfString:@"-"withString:@""];

                

                if ([realPhoneisEqualToString:phoneNum]) {

                    returnABHelperExistSpecificContact;

                }

            }

        }

    }

    

    CFRelease(addressBook);

    returnABHelperNotExistSpecificContact;

}


@end




使用样例:

//发短信给用户+打电话给用户

    if (index ==0) {

//打电话

        TodoSome todo_1 = ^(void){

            [[UIApplicationsharedApplication] openURL:[NSURLURLWithString:[NSStringstringWithFormat:@"tel://%@",self.dataDict[@"tenderInfo"][@"customTelephone"]]]];

        };

        TodoSome todo_2 = ^(void){

            NSString *phone =self.dataDict[@"tenderInfo"][@"customTelephone"];

            NSString *name =self.dataDict[@"tenderInfo"][@"customName"];

            NSString *remark =self.dataDict[@"tenderInfo"][@"title"];

            

            if ([AddressBookHelperexistPhone:phone] == ABHelperExistSpecificContact) {

                [ToolstoolAlertWithTitle:@"温馨提示"andMessage:[NSStringstringWithFormat:@"手机号码:%@已存在通讯录",phone]byController:selfsureBlock:nil];

            }else {

                if ([AddressBookHelperaddContactName:name phoneNum:phone withLabel:remark]) {

                    [ToolstoolAlertWithTitle:@"温馨提示"andMessage:@"添加到通讯录成功"byController:selfsureBlock:nil];

                }else {

                    [ToolstoolAlertWithTitle:@"温馨提示"andMessage:@"添加到通讯录失败"byController:selfsureBlock:nil];

                }

            }

        };

        TodoSome todo_3 = ^(void){

            UIPasteboard * pasteboard = [UIPasteboardgeneralPasteboard];

            [pasteboard setString:self.dataDict[@"tenderInfo"][@"customTelephone"]];

        };

        [ToolstoolAlertWithTitleArray:@[@"拨打客户电话",@"保存电话到通讯录",@"复制"]doSomething:@[todo_1,todo_2,todo_3]byController:self];

    }elseif (index == 1) {

//发短信

        if(![MFMessageComposeViewControllercanSendText])return;

        MFMessageComposeViewController *smsController = [[MFMessageComposeViewControlleralloc] init];

        smsController.messageComposeDelegate =self;

        smsController.recipients = [NSArrayarrayWithObject:self.dataDict[@"tenderInfo"][@"customTelephone"]];

        [selfpresentViewController:smsControlleranimated:YEScompletion:nil];

    }



工具:http://blog.csdn.net/liushihua147/article/details/53408975


block:

typedef void(^TodoSome)(void);


Alert:

+ (void)toolAlertWithTitle:(NSString *)title andMessage:(NSString *)message byController:(UIViewController *)controller sureBlock:(void (^)(void))sureBlock {

    [ToolstoolAlertWithTitle:titleandMessage:message andSureTitle:@"确定"byController:controller sureBlock:^{

        if (sureBlock) {

            sureBlock();

        }

    }];

}

+ (void)toolAlertWithTitle:(NSString *)title andMessage:(NSString *)message andSureTitle:(NSString *)sure byController:(UIViewController *)controller sureBlock:(void (^)(void))sureBlock {

    

    if (kSystemVersion >=8.0) {

        

        UIAlertController *alertC = [UIAlertControlleralertControllerWithTitle:titlemessage:message preferredStyle:UIAlertControllerStyleAlert];

        [alertC addAction:[UIAlertActionactionWithTitle:sure style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {

            if (sureBlock) {

                sureBlock();

            }

            

        } ]];

        [controller presentViewController:alertCanimated:YEScompletion:nil];

    }else {

        

        Tools *tool = [ToolstoolManager];

        UIAlertView *alertV = [[UIAlertViewalloc] initWithTitle:titlemessage:message delegate:toolcancelButtonTitle:nilotherButtonTitles:sure, nil];

        TodoSome tod1 = ^(void){

            if (sureBlock) {

                sureBlock();

            }

        };

        tool.doSomething = [NSMutableArrayarrayWithObjects:tod1, nil];

        [alertV show];

    }

}

+ (instancetype)toolManager {

    staticdispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        _instace = [[selfalloc] init];

    });

    return_instace;

}

#pragma mark 弹出提示视图

+ (void)toolAlertWithTitleArray:(NSArray *)titles doSomething:(NSArray<TodoSome> *)doSomethings byController:(UIViewController *)controller{

    

    if (kSystemVersion >=8.0) {

        UIAlertController *alertC = [UIAlertControlleralertControllerWithTitle:nilmessage:nilpreferredStyle:UIAlertControllerStyleActionSheet];

        

        for (NSInteger index =0; index < titles.count; index++) {

            UIAlertAction *action = [UIAlertActionactionWithTitle:titles[index]style:UIAlertActionStyleDefaulthandler:^(UIAlertAction *_Nonnull action) {

                TodoSome todoSomething = doSomethings[index];

                todoSomething();

            }];

            [alertC addAction:action];

        }

        UIAlertAction *action = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:nil];

        [alertC addAction:action];

        

        [controller presentViewController:alertCanimated:YEScompletion:nil];

    }else {

        Tools *tool = [ToolstoolManager];

        UIActionSheet *sheet = [[UIActionSheetalloc] initWithTitle:nildelegate:tool cancelButtonTitle:@"取消"destructiveButtonTitle:nilotherButtonTitles: nil];

        for (NSInteger index =0; index < titles.count; index++) {

            [sheet addButtonWithTitle:titles[index]];

            tool.doSomething = [doSomethingsmutableCopy];

        }

        [sheet showInView:controller.view];

    }

}







猜你喜欢

转载自blog.csdn.net/liushihua147/article/details/53408744