博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS通讯录
阅读量:5948 次
发布时间:2019-06-19

本文共 9424 字,大约阅读时间需要 31 分钟。

hot3.png

1.添加或删除通信录,无需跳转到通讯录界面

/** 添加通讯录 */+ (void)requestAddRLNumIntoContact{    if ([self isExistContactRLNum]) {        debugLog(@"联系人已存在");    }else{        [self createRLNum];    }}/**访问通讯录并且检查是否联系已存在*/+ (BOOL)isExistContactRLNum{    //记录用户是否允许我们访问通讯录    int __block tip = 0;    BOOL __block isExist = NO;        //声明通讯簿    ABAddressBookRef addBook = nil;        //授权    CFErrorRef error = NULL;    addBook = ABAddressBookCreateWithOptions(NULL, &error);        //创建初始信号量为0的信号,实现NSOperation的依赖关系    dispatch_semaphore_t sema = dispatch_semaphore_create(0);        //申请访问权限    ABAddressBookRequestAccessWithCompletion(addBook, ^(bool granted, CFErrorRef error) {        if (!granted) {//用户不允许            tip=1;                        dispatch_async(dispatch_get_main_queue(), ^{                popAlertView *popView = [[popAlertView alloc] initWithNib:[UIImage imageNamed:@"smart_success_"] tipsLabStr:@"是否允许请求访问你的通讯录" tipsBtnStr:@"确定"];                [popView.showBtn addTarget:self action:@selector(ensurePushContacts) forControlEvents:UIControlEventTouchUpInside];                [popView show];                            });                    }else{            //获取联系人的数组            CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);            //获取联系人总数            CFIndex number = ABAddressBookGetPersonCount(addBook);            //进行遍历            for (NSInteger i = 0; i < number; i++) {                //获取单个联系人对象                ABRecordRef people = CFArrayGetValueAtIndex(allLinkPeople, i);                //获取联系人名字                NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));                if ([firstName isEqualToString:@"智慧办公"]) {                    isExist = YES;                }            }                    }                if (tip) {            dispatch_async(dispatch_get_main_queue(), ^{                popAlertView *popView = [[popAlertView alloc] initWithNib:[UIImage imageNamed:@"smart_success_"] tipsLabStr:@"是否允许请求访问你的通讯录" tipsBtnStr:@"确定"];                [popView.showBtn addTarget:self action:@selector(ensurePushContacts) forControlEvents:UIControlEventTouchUpInside];                [popView show];                            });                        isExist = YES;        }                //发送一次信号        dispatch_semaphore_signal(sema);            });    //等待信号触发    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);    return isExist;}/**添加通讯录*/+ (void)createRLNum{    CFErrorRef error = NULL;        //创建一个通讯录操作对象    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);        //创建一条新的联系人记录    ABRecordRef newRecord = ABPersonCreate();        //为新联系人记录添加属性值    ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)(@"智慧办公"), &error);        //创建一个多值属性(电话)    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)(@"02096911328"), kABPersonPhoneMobileLabel, NULL);    ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);        //添加记录到通讯录操作对象    ABAddressBookAddRecord(addressBook, newRecord, &error);        //保存通讯录操作对象    ABAddressBookSave(addressBook, &error);            //通过此接口访问系统通讯录    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {        if (granted) {            debugLog(@"添加联系人成功");        }    });        CFRelease(multi);    CFRelease(newRecord);    CFRelease(addressBook);}/**清空通讯录*/+(void)deleteContacts{    CFErrorRef error = NULL;        //创建一个通讯录操作对象    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {        if (granted && !error) {            CFArrayRef personArray = ABAddressBookCopyArrayOfAllPeople(addressBook);            CFIndex personCount = ABAddressBookGetPersonCount(addressBook);                        if (personCount <= 0) {                return;            }                        for (int i = 0; i < personCount; i++) {                ABRecordRef ref = CFArrayGetValueAtIndex(personArray, i);                // 删除联系人                ABAddressBookRemoveRecord(addressBook, ref, nil);            }                        // 保存通讯录操作对象            ABAddressBookSave(addressBook, &error);            CFRelease(addressBook);                        dispatch_async(dispatch_get_main_queue(), ^{                if (!error) {                } else {                }            });        }    });}+ (void)ensurePushContacts{    NSString *string = @"prefs:root=Privacy&path=CONTACTS";    NSURL *url = [NSURL URLWithString:string];    [[UIApplication sharedApplication] openURL:url];}

 

2.获取点击选择的通信人名字和电话

////  ViewController.m//  WWW////  Created by ling on 16/8/16.//  Copyright © 2016年 ldccomputer. All rights reserved.//#import "ViewController.h"#import 
#import
#import "AppDelegate.h"@interface ViewController ()
@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init]; peoplePicker.peoplePickerDelegate = self; [self authoriy]; [self presentViewController:peoplePicker animated:YES completion:nil];}/** * 授权注册 */- (void)authoriy{ if (&ABAddressBookRequestAccessWithCompletion != NULL) { //iOS6 ABAddressBookRef abRef = ABAddressBookCreateWithOptions(NULL, NULL); if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) { //如果没申请过权限,申请权限 ABAddressBookRequestAccessWithCompletion(abRef, ^(bool granted, CFErrorRef error) { if (granted) { //granted代表是否同意授予权限 //查询通讯录所有联系人 [self getContacts]; } }); }else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){ //权限已经授予 [self getContacts]; }else{ //权限不被授予 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请您设置允许APP访问您的通讯录\n设置>通用>访问权限" delegate:self cancelButtonTitle:@"" otherButtonTitles:nil, nil]; [alert show]; return; } if (abRef) { CFRelease(abRef); } }}/** * 获取通讯录所有联系人 */- (void)getContacts{ //获取所有通讯录单元信息 ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL); //取全部联系人 CFArrayRef allPerson = ABAddressBookCopyArrayOfAllPeople(addressBook); CFIndex number = ABAddressBookGetPersonCount(addressBook); //遍历 for (NSInteger i = 0; i < number; i++) { ABRecordRef people = CFArrayGetValueAtIndex(allPerson, i); //联系人的姓名 NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty); NSString *middleName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonMiddleNameProperty); NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty); NSString *nameString = [NSString stringWithFormat:@"%@%@%@",firstName,middleName,lastName]; // NSLog(@"name : %@",nameString); //联系人电话 ABMutableMultiValueRef phoneMutil = ABRecordCopyValue(people, kABPersonPhoneProperty); NSMutableArray *phones = [NSMutableArray array]; for (int i = 0; i < ABMultiValueGetCount(phoneMutil); i ++) { NSString *phoneLabel = (__bridge NSString *)ABMultiValueCopyLabelAtIndex(phoneMutil, i);#warning _$!
!$_取出固话和电话号码,但400开头的无法获取 if ([phoneLabel isEqualToString:@"_$!
!$_"]) { [phones addObject:(__bridge id _Nonnull)(ABMultiValueCopyValueAtIndex(phoneMutil, i))]; } }// NSLog(@"phone:%@",phones); }}/** * 选择后的代理 */- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{ ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty); CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef, identifier); CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef, index); CFStringRef anFullName = ABRecordCopyCompositeName(person); [peoplePicker dismissViewControllerAnimated:YES completion:^{ [self dismissViewControllerAnimated:YES completion:^{ self.contactPhoneNumber = (__bridge NSString *)(value); self.contactName = (__bridge NSString *)(anFullName); [[NSNotificationCenter defaultCenter] postNotificationName:@"Num" object:self.contactPhoneNumber userInfo: @{@"name" : self.contactName}]; }]; }]; self.contactPhoneNumber = (__bridge NSString *)(value); self.contactName = (__bridge NSString *)(anFullName); NSLog(@" notif1 :%@ %@",self.contactPhoneNumber,self.contactName);}-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{ [self dismissViewControllerAnimated:YES completion:nil];}@end

 

转载于:https://my.oschina.net/u/2346786/blog/727237

你可能感兴趣的文章
MaxCompute 图计算用户手册(上)
查看>>
自带科技基因,打造纯原创IP,“燃烧小宇宙”获数千万A轮融资
查看>>
未能加载文件或程序集&quot;Newtonsoft.Json, Version=4.5.0.0
查看>>
C#多线程编程系列(二)- 线程基础
查看>>
Jenkins 内置变量(学习笔记二十四)
查看>>
PostgreSQL 10.1 手册_部分 II. SQL 语言_第 13 章 并发控制_13.2. 事务隔离
查看>>
虚拟机概念
查看>>
【云周刊】第195期:全球首家!阿里云获GNTC2018 网络创新大奖 成唯一获奖云服务商...
查看>>
【VS】使用vs2017自带的诊断工具(Diagnostic Tools)诊断程序的内存问题
查看>>
AutoScaling 支持从实例启动模板创建实例
查看>>
Mysql 查看视图、存储过程、函数、触发器
查看>>
Java提高篇(二):IO字节流、字符流和处理流
查看>>
云HBase集群的规划
查看>>
hello dato--graphlab create
查看>>
一个优质男朋友的标准
查看>>
浩鲸科技和京东加入 OpenMessaging 开源标准社区
查看>>
spring 注入方式
查看>>
FileZilla Client 3.42.0 beta1 发布,流行的 FTP 解决方案
查看>>
深度学习之迁移学习介绍与使用
查看>>
Qt学习笔记(一)-文件目录与术语解释
查看>>