IOS 通讯录的访问和修改的实现
在iOS端可以通过AddressBook或者AddressBookUI两个框架实现,区别是第二个框架带视图,一般使用第一个框架就够了。
下面介绍AddressBook框架的使用,注意这个是C语言框架,使用起来比较麻烦。
①请求授权
先判断授权状态,如果未授权则进行授权。
// 1.主动请求授权,先判断授权状态 NSInteger state = ABAddressBookGetAuthorizationStatus(); if (state == kABAuthorizationStatusAuthorized) { NSLog(@"已经授权"); }else{ ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL); ABAddressBookRequestAccessWithCompletion(book, ^(bool granted, CFErrorRef error) { if (granted) { NSLog(@"授权成功"); }else{ NSLog(@"授权失败"); } }); }
②获取通讯录的联系人
c语言没有对象,通过一些以Ref结尾的指针来获取数据。
注意C语言数组的规模通过函数获取,拿到元素也要通过函数。
注意一些枚举值以k开头。
注意电话是一个数组。
// 先判断授权状态 if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) { NSLog(@"未授权"); return; } ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL); CFArrayRef persons = ABAddressBookCopyArrayOfAllPeople(book); CFIndex count = CFArrayGetCount(persons); for (NSInteger i = 0; i < count; i++) { ABRecordRef person = CFArrayGetValueAtIndex(persons, i); CFStringRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty); CFStringRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty); ABMutableMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty); NSLog(@"联系人:%@ %@",lastName,firstName); NSInteger cnt = ABMultiValueGetCount(phones); for (int j = 0; j < cnt; j++) { CFStringRef phone = ABMultiValueCopyValueAtIndex(phones, j); NSLog(@"电话:%@ ",phone); } }
③修改通讯录联系人
首先拿到通讯录中的人,然后调用SetValue方法来修改值。
最后不要忘记保存。
// 先判断授权状态 if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) { NSLog(@"未授权"); return; } ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL); CFArrayRef persons = ABAddressBookCopyArrayOfAllPeople(book); ABRecordRef person = CFArrayGetValueAtIndex(persons, 0); ABRecordSetValue(person, kABPersonLastNameProperty, @"changed", NULL); ABAddressBookSave(book, NULL);
④添加一个联系人
注意添加电话时应创建MultiValue。
// 先判断授权状态 if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) { NSLog(@"未授权"); return; } ABAddressBookRef book = ABAddressBookCreateWithOptions(NULL, NULL); CFArrayRef persons = ABAddressBookCopyArrayOfAllPeople(book); CFIndex count = CFArrayGetCount(persons); for (NSInteger i = 0; i < count; i++) { ABRecordRef person = CFArrayGetValueAtIndex(persons, i); CFStringRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty); CFStringRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty); ABMutableMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty); NSLog(@"联系人:%@ %@",lastName,firstName); NSInteger cnt = ABMultiValueGetCount(phones); for (int j = 0; j < cnt; j++) { CFStringRef phone = ABMultiValueCopyValueAtIndex(phones, j); NSLog(@"电话:%@ ",phone); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。