iOSContactsUI(聯絡人)

凌浩雨發表於2018-01-23

1. 帶UI的通訊錄

#import "ViewController.h"
#import <AddressBookUI/AddressBookUI.h>

@interface ViewController ()<ABPeoplePickerNavigationControllerDelegate>
@end

@implementation ViewController
// 觸控顯示
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //1. 建立聯絡人選擇控制器
    ABPeoplePickerNavigationController *picker = [ABPeoplePickerNavigationController new];
    
    //2. 設定代理 --> 注意不是 Delegate
    picker.peoplePickerDelegate = self;
    
    //3. 模態檢視彈出
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 選中某個聯絡人時呼叫
/**
 以下兩個方法,如果同時實現, 只會執行didSelectPerson: 方法
 兩個方法, 應該實現一個即可
 */

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person
{
    //需求: 獲取姓名 和 電話
    
    //1. 獲取姓名
    //Record --> 就相當於一條記錄
    //lastName: 姓
    CFStringRef lastName = ABRecordCopyValue(person, kABPersonLastNameProperty);
    NSString *lastNameStr = (__bridge NSString *)(lastName);
    NSLog(@"lastNameStr: %@",lastNameStr);
    
    CFStringRef firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *firstNameStr = (__bridge NSString *)(firstName);
    NSLog(@"firstNameStr: %@",firstNameStr);
    
    CFRelease(lastName);
    CFRelease(firstName);
    
    //2. 獲取電話 --> 電話是多資料型別
    ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
    
    //2.1 獲取電話的個數
    CFIndex count = ABMultiValueGetCount(phones);
    
    //2.2 遍歷聯絡人
    for (CFIndex i = 0 ; i < count; i++) {
        //2.3 獲取聯絡電話的標籤
        NSString *label = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(phones,  i);
        NSLog(@"label: %@",label);
        
        //2.4 獲取聯絡電話
        NSString *value = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones,  i));
        NSLog(@"value: %@",value);
    }
     
    //3. 釋放 CF 物件
    CFRelease(phones);

    //Core Foundation 和 Fundation 橋接的問題 --> 面試題
    //1. 有幾種方式 2. 注意事項 注意釋放 CF 物件
    //將 CF 物件給 Foundatian
   
    //1. (__bridge type)<#expression#>) : 只是讓 Foundation 框架暫時使用 CF 框架物件
    //2. (__bridge_transfer )) / CFBridgingRelease : CF框架移交物件的管理權給 Foundation 框架
    //將 Foundatian給 CF 物件 不常用
    //3. (__bridge_retained <#CF type#>)<#expression#>)
}

#pragma mark 選中聯絡人的某個屬性的時候呼叫

//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
//{
//    NSLog(@"%d",property);
//}

#pragma mark 取消選中聯絡人時呼叫
// 在 iOS7下, 必須實現此方法, 否則就會崩潰
//- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
//{
//    NSLog(@"%s",__func__);
//}

@end

2. 不帶UI的通訊錄

1). AppDelegate授權

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //通訊錄授權 --> iOS6開始, 必須授權才能上架
    /**
     kABAuthorizationStatusNotDetermined = 0   使用者未選擇
     kABAuthorizationStatusRestricted,         一些許可配置阻止了通訊錄的互動
     kABAuthorizationStatusDenied,             使用者拒絕
     kABAuthorizationStatusAuthorized          使用者授權
     */

    //1. 獲取授權狀態
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();
    
    //2. 建立 AddrssBook
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    
    //3. 沒有授權時就授權
    if (status == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            //3.1 判斷出錯
            if (error) {
                return;
            }
            
            //3.2 判斷是否授權
            if (granted) {
                NSLog(@"已經授權");
            } else {
                NSLog(@"沒有授權");
            }
        });
    }
    
    //4. 釋放 CF 物件
    CFRelease(addressBook);
    return YES;
}

2). 程式碼

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

@implementation ViewController
// 觸控顯示
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 點選螢幕獲取所有聯絡人資訊
    
    //1. 判斷是否授權成功, 授權成功才能獲取資料
    if ( ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
     
        //2. 建立通訊錄
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        
        //3. 獲取聯絡人  --> Array
        CFArrayRef peosons = ABAddressBookCopyArrayOfAllPeople(addressBook);
        
        //4. 遍歷聯絡人來獲取資料(姓名和電話)
        CFIndex count = CFArrayGetCount(peosons);
        
        for (CFIndex i = 0 ; i < count; i++) {
            
            //5. 獲取單個聯絡人
            ABRecordRef person = CFArrayGetValueAtIndex(peosons, i);
            
            //6. 獲取姓名
            NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
            NSString *firstName  = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
            NSLog(@"lastName: %@, firstName: %@", lastName, firstName);
            
            //7. 獲取電話
            ABMultiValueRef phones = ABRecordCopyValue(person, kABPersonPhoneProperty);
            
            //7.1 獲取 count
            CFIndex phoneCount = ABMultiValueGetCount(phones);
            
            //7.2 遍歷ABMultiValueRef
            for (CFIndex i = 0; i < phoneCount; i++) {
                NSString *label = CFBridgingRelease(ABMultiValueCopyLabelAtIndex(phones, i));
                NSString *value = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phones, i));
                NSLog(@"label: %@, value: %@",label, value);
            }
            
            NSLog(@"

");
            
            //8.1 釋放 CF 物件
            CFRelease(phones);
        }       
        //8.1 釋放 CF 物件
        CFRelease(peosons);
        CFRelease(addressBook);
    }
}

@end

3. iOS9 通訊錄(新增)

#import "ViewController.h"
#import <ContactsUI/ContactsUI.h>

@interface ViewController () <CNContactPickerDelegate>
@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // 1. 建立控制器
    CNContactPickerViewController *contact = [CNContactPickerViewController new];
    // 2. 設定代理
    contact.delegate = self;
    // 3. 模態彈出
    [self presentViewController:contact animated:YES completion:nil];
}

#pragma mark 選擇聯絡人的時候呼叫
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    // 1. 獲取姓名
    NSLog(@"givenName: %@, familyName: %@", contact.givenName, contact.familyName);
    // 2. 獲取電話
    for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
        CNPhoneNumber *phoneNumber = labeledValue.value;
        NSLog(@"phoneNumber: %@", phoneNumber.stringValue);
    }
}

#pragma mark 實現了此方法就可以選擇多個聯絡人
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
    for (CNContact *contact in contacts) {
        
        NSLog(@"givenName: %@, familyName: %@", contact.givenName, contact.familyName);
        for (CNLabeledValue *labeledValue in contact.phoneNumbers) {
            NSLog(@"label: %@", labeledValue.label);
            CNPhoneNumber *phoneNumber = labeledValue.value;
            NSLog(@"phoneNumber: %@", phoneNumber.stringValue);
        }
    }
}
@end


相關文章