IOS基础知识记录九(调用AddressBook地址博信息)

手机访问地址薄

1.首先加入包AddressBookUI、AddressBook并引入类。其次加入地址薄调用遵循的协议
#import <AddressBookUI/AddressBookUI.h>
#import <AddressBook/AddressBook.h>

//协议
ABPeoplePickerNavigationControllerDelegate


2.实现协议的部分方法,用来处理选择地址薄信息或者关闭地址操作等
//当地址关闭时处理部分信息: 如果关闭模态等,在第七记录中已经写过
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker

//处理选择地址薄后怎么解析person信息
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person


3.解析选择的地址薄信息
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    NSString *firstName, *lastName;
    
//对于地址薄中的firstName, lastName都是唯一的不会重复,故直接转化字符串
    firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    
      //电话是多个, 要用数组来处理
    ABMultiValueRef telRef;
        telRef = ABRecordCopyValue(person,  kABPersonPhoneProperty);
    if (ABMultiValueGetCount(telRef) > 0) {
        NSString * tel = (__bridge NSString *)ABMultiValueCopyValueAtIndex(telRef, 1);
    }
    //Email 和电话类似
    ABMultiValueRef emailRef;
    emailRef = ABRecordCopyValue(person, kABPersonEmailProperty);
    if (ABMultiValueGetCount(emailRef) > 0) {
        email.text = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emailRef, 0);
    }
    
 //而相对于地址来说比较复杂。 地址信息包含信息量比较大
    ABMultiValueRef addressRef;
    NSDictionary *addressDic;
    NSString *zipCode;
    
    addressRef = ABRecordCopyValue(person, kABPersonAddressProperty);
    if (ABMultiValueGetCount(addressRef) > 0) {
        addressDic = (__bridge NSDictionary *)ABMultiValueCopyValueAtIndex(addressRef, 0);
        zipCode = [addressDic objectForKey: @"ZIP"];
        
    }

    //关闭模态
    [self dismissViewControllerAnimated: YES completion: nil];
    return  NO;
}

你可能感兴趣的:(ios,Objective-C,AddressBook,地址薄,电话簿)