在 iOS 中,若需要讓使用者從系統通訊錄選擇聯絡人,可以使用 AddressBookUI 提供的 ABPeoplePickerNavigationController,而不是自行建立通訊錄列表。
專案需要引入 AddressBook 與 AddressBookUI 兩個框架,才能使用通訊錄與選擇器相關 API。
ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init]; peoplePicker.peoplePickerDelegate = self; [self presentViewController:peoplePicker animated:YES completion:nil];
當使用者選取某個電話屬性時,可透過 ABPeoplePickerNavigationControllerDelegate 的 didSelectPerson:property:identifier: 取得 ABRecordRef、ABPropertyID 與 ABMultiValueIdentifier,再複製對應電話值。
ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef, identifier);
CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef, index);
[self dismissViewControllerAnimated:YES completion:^{
self.textField.text = (__bridge NSString *)value;
}];這個做法適合 iOS 8 之後的專案;若需要支援更舊版本,則要改用其他 API 並注意不相容問題。