您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 通訊錄開發:讀取聯絡人資訊完整教學

編輯:iOS 開發綜合

讀取通訊錄中的聯絡人,一般流程是先查詢記錄,再逐一存取記錄的屬性;屬性又可分為單值與多值兩類。本文以一個實作為主線,涵蓋聯絡人查詢、單值與多值屬性存取,以及聯絡人圖片的讀取。

這個範例會從裝置讀取通訊錄,以表視圖列出,支援搜尋過濾,點擊可進入詳細資訊頁。

前置準備

一、加入框架:為專案加入 AddressBook.framework 與 AddressBookUI.framework。

二、引入標頭檔:

#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

一、查詢聯絡人記錄

通訊錄資料庫不支援 SQL,只能透過兩個 C 函式取得記錄:

// 取得所有聯絡人
CFArrayRef ABAddressBookCopyArrayOfAllPeople(ABAddressBookRef addressBook);

// 依姓名查詢,name 為前綴關鍵字
CFArrayRef ABAddressBookCopyPeopleWithName(ABAddressBookRef addressBook, CFStringRef name);

兩個函式都需要傳入通訊錄物件,它以 ABAddressBookCreateWithOptions 建立(iOS 6 之前用的是 ABAddressBookCreate):

ABAddressBookRef ABAddressBookCreateWithOptions(CFDictionaryRef options, CFErrorRef *error);

options 目前是保留參數,傳 NULL 即可;error 用來接收錯誤資訊。

二、授權流程

// ViewController.h
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import "DetailViewController.h"

@interface ViewController : UITableViewController
<UISearchBarDelegate, UISearchDisplayDelegate>

@property (nonatomic, strong) NSArray *listContacts;
- (void)filterContentForSearchText:(NSString *)searchText;

@end

listContacts 用來裝載聯絡人記錄陣列,filterContentForSearchText: 則是負責過濾與查詢的方法。

- (void)viewDidLoad
{
    [super viewDidLoad];

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

    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted) {
            [self filterContentForSearchText:@""];   // 查詢全部
        }
    });

    CFRelease(addressBook);
}

ABAddressBookRequestAccessWithCompletion 的作用是向使用者請求存取通訊錄。首次呼叫時系統會彈出授權對話框,使用者同意後才會執行後面的程式碼塊。

由於請求與回呼都是非同步的,你會看到表視圖先出現,稍後結果才填入。從 iOS 6 起這一步是必須的,少了它就完全無法存取通訊錄。

三、實作查詢方法

- (void)filterContentForSearchText:(NSString *)searchText
{
    // 未授權則直接退出
    if (ABAddressBookGetAuthorizationStatus() != kABAuthorizationStatusAuthorized) {
        return;
    }

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

    if ([searchText length] == 0) {
        // 查詢全部
        self.listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
    } else {
        // 條件查詢
        CFStringRef cfSearchText = (CFStringRef)CFBridgingRetain(searchText);
        self.listContacts = CFBridgingRelease(ABAddressBookCopyPeopleWithName(addressBook, cfSearchText));
        CFRelease(cfSearchText);
    }

    [self.tableView reloadData];
    CFRelease(addressBook);
}

這裡有兩個 ARC 橋接重點值得記住。CFArrayRef 無法直接賦值給 NSArray* 屬性,常見處理有兩種:

self.listContacts = (__bridge NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
// 或
self.listContacts = CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));

兩者的差別在於所有權。(__bridge NSArray *) 只是單純的型別轉換,不轉讓所有權,因此原物件仍需自行釋放。CFBridgingRelease 則是「轉型並把所有權交給 ARC」,之後就不必再理會。

反方向的 CFBridgingRetain 是 Foundation 轉 Core Foundation,並把物件的持有權交給呼叫者,所以你必須負責 CFRelease 它。

最後要留意:Core Foundation 的型別不受 ARC 管理,需手動釋放,CFRelease 的角色等同於 MRC 下的 release。

四、搜尋欄的串接

#pragma mark - UISearchBarDelegate

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self filterContentForSearchText:@""];   // 還原為全部
}

#pragma mark - UISearchDisplayController Delegate

// 搜尋字串改變時通知表視圖重新載入
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
    shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString];
    return YES;
}

五、讀取單值屬性

單值屬性是只有一個值的欄位,由一批常數定義:kABPersonFirstNameProperty(名字)、kABPersonLastNameProperty(姓氏)、kABPersonMiddleNameProperty(中間名)、kABPersonPrefixProperty(前綴)、kABPersonSuffixProperty(後綴)、kABPersonNicknameProperty(暱稱)、kABPersonFirstNamePhoneticProperty 與 kABPersonLastNamePhoneticProperty(拼音或音標)、kABPersonOrganizationProperty(組織)、kABPersonJobTitleProperty(頭銜)、kABPersonDepartmentProperty(部門)、kABPersonNoteProperty(備註)。

讀取用的函式是 ABRecordCopyValue:

CFTypeRef ABRecordCopyValue(ABRecordRef record, ABPropertyID property);

回傳的 CFTypeRef 是 Core Foundation 的泛型,可代表任何 CF 型別。在 cellForRowAtIndexPath: 中:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:CellIdentifier];
    }

    ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:[indexPath row]]);

    NSString *firstName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonFirstNameProperty));
    firstName = firstName != nil ? firstName : @"";

    NSString *lastName = CFBridgingRelease(ABRecordCopyValue(thisPerson, kABPersonLastNameProperty));
    lastName = lastName != nil ? lastName : @"";

    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

    CFRelease(thisPerson);
    return cell;
}

這裡同樣是「Foundation 轉 CF 用 Retain、CF 轉 Foundation 用 Release」的配對,並在最後 CFRelease 掉記錄物件。

六、把選取的聯絡人傳給詳情頁

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        ABRecordRef thisPerson = CFBridgingRetain([self.listContacts objectAtIndex:[indexPath row]]);

        DetailViewController *detailViewController = [segue destinationViewController];

        ABRecordID personID = ABRecordGetRecordID(thisPerson);
        NSNumber *personIDAsNumber = [NSNumber numberWithInt:personID];
        detailViewController.personIDAsNumber = personIDAsNumber;

        CFRelease(thisPerson);
    }
}

DetailViewController 只需多一個 NSNumber* 型別的 personIDAsNumber 屬性,即可接收記錄 ID。

七、讀取多值屬性

多值屬性是含多個值的集合,例如電話、Email、URL、親屬關係、地址、即時通訊帳號與社群帳號,分別對應 kABPersonPhoneProperty、kABPersonEmailProperty、kABPersonURLProperty、kABPersonRelatedNamesProperty、kABPersonAddressProperty、kABPersonInstantMessageProperty、kABPersonSocialProfileProperty。其中前四者是 kABMultiStringPropertyType,後三者是 kABMultiDictionaryPropertyType。

多值屬性由 label(標籤)、value(值)與 ID 組成,標籤與值可以重複,ID 則唯一。

存取方式同樣先用 ABRecordCopyValue,只是回傳型別變成 ABMultiValueRef,接著再用其他函式取出內容:

CFArrayRef ABMultiValueCopyArrayOfAllValues(ABMultiValueRef multiValue);
CFStringRef ABMultiValueCopyLabelAtIndex(ABMultiValueRef multiValue, CFIndex index);
ABMultiValueIdentifier ABMultiValueGetIdentifierAtIndex(ABMultiValueRef multiValue, CFIndex index);

讀取 Email 的範例:

ABMultiValueRef emailsProperty = ABRecordCopyValue(person, kABPersonEmailProperty);
NSArray *emailsArray = CFBridgingRelease(ABMultiValueCopyArrayOfAllValues(emailsProperty));

for (int index = 0; index < [emailsArray count]; index++) {
    NSString *email = [emailsArray objectAtIndex:index];
    NSString *emailLabel = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(emailsProperty, index));

    if ([emailLabel isEqualToString:(NSString *)kABWorkLabel]) {
        [self.lblWorkEmail setText:email];
    } else if ([emailLabel isEqualToString:(NSString *)kABHomeLabel]) {
        [self.lblHomeEmail setText:email];
    } else {
        NSLog(@"%@: %@", @"其它 Email", email);
    }
}

CFRelease(emailsProperty);

kABWorkLabel 與 kABHomeLabel 是常見標籤,另有 kABOtherLabel。電話號碼的寫法完全相同,只是常數換成 kABPersonPhoneMobileLabel(手機)、kABPersonPhoneIPhoneLabel(iPhone 號碼),此外還有 kABPersonPhoneMainLabel、kABPersonPhoneHomeFAXLabel、kABPersonPhoneWorkFAXLabel 與 kABPersonPhonePagerLabel。

八、讀取聯絡人圖片

CFDataRef ABPersonCopyImageData(ABRecordRef person);
bool ABPersonHasImageData(ABRecordRef person);
if (ABPersonHasImageData(person)) {
    NSData *photoData = CFBridgingRelease(ABPersonCopyImageData(person));
    if (photoData) {
        [self.imageView setImage:[UIImage imageWithData:photoData]];
    }
}

ABPersonCopyImageData 回傳 CFDataRef,對應的 Foundation 型別是 NSData*,轉型後交給 UIImage 的 imageWithData: 即可。

實務提醒

ABAddressBook 這套 C API 從 iOS 9 起已被 Contacts.framework 取代,新專案應改用 CNContactStore 與 CNContact。若維護的是舊專案,除了上述 API,也別忘了 Info.plist 中的 Privacy - Contacts Usage Description 若缺失,授權請求會直接失敗。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved