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); } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!