IOS编程之通讯录

 

//

//  ViewController.m

//  LearnAddressBook0

//

//  Created by Mac on 14-7-28.

//  Copyright (c) 2014年 Digital media technology. All rights reserved.

//


#import "ViewController.h"

#import <AddressBook/AddressBook.h>

#import <AddressBookUI/AddressBookUI.h>

#import "Contact.h"


@interfaceViewController () <ABPeoplePickerNavigationControllerDelegate>


@property (weak, nonatomic) IBOutletUITextField *phoneNumTextField;


@end


@implementation ViewController


- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}


- (IBAction)btn:(id)sender {

    

    //获得通讯录的所有联系人数据,并且打印出来

    [selfloadAddressBook];

    

}


- (IBAction)addAContacts:(id)sender {

    

    Contact *contact = [[Contact alloc] init];

    contact.firstName = @"new";

    

    [selfaddContact:contact addressBookRef:[selfcreateAddressBook]];

    

    

}


- (IBAction)deleteAContacts:(id)sender {

    

    [selfdeleteContact:@"Jenny"addressBookRef:[selfcreateAddressBook]];

    

}


- (IBAction)choseAContact:(id)sender {

    

    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationControlleralloc] init];

    picker.peoplePickerDelegate = self;

    [selfpresentViewController:picker animated:YEScompletion:^{}];

    

}


//1、查询通讯录信息

-(ABAddressBookRef)createAddressBook{

    ABAddressBookRef addressBook;

    

    if ([[UIDevicecurrentDevice].systemVersion floatValue] >= 6.0)//判断ios版本

    {

        

        addressBook = ABAddressBookCreateWithOptions(NULL, NULL);

        

        //等待同意后向下执行

        

        dispatch_semaphore_t sema = dispatch_semaphore_create(0);

        

        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {

            

            dispatch_semaphore_signal(sema);

            

        });

        

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);


    } else {

        addressBook = ABAddressBookCreate();

        

    }

    return addressBook;

}


//2.获取联系人信息(Contact为自定义联系人信息类)

-(void)loadAddressBook{

    

    NSMutableArray *contactArray = [[NSMutableArrayalloc] init];

    

    ABAddressBookRef addressBook = [selfcreateAddressBook];

    

    //是否有访问通讯录的权限

    if (!addressBook) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"通讯录未有权限,请在设置-隐私中进行更改" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];

        [alertView show];

    }

    

    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);

    

    //获取通讯录联系人的名字信息

    NSString *firstName, *lastName, *fullName;

    

    for (id person in (__bridge NSArray*)allPeople) {

        //Contact *contact = [[Contact alloc] init];

        

        firstName = (__bridgeNSString*)ABRecordCopyValue((__bridgeABRecordRef)(person), kABPersonFirstNameProperty);

        

        NSLog(@"first is:%@",firstName);

        

        if (firstName == nil) {

            firstName = @"";

        }

        

        lastName = (__bridgeNSString*)ABRecordCopyValue((__bridgeABRecordRef)(person), kABPersonLastNameProperty);

        

        NSLog(@"last name is:%@",lastName);

        

        if (lastName == nil) {

            lastName = @"";

        }

        

        fullName = [lastName stringByAppendingFormat:@"%@",firstName];

        NSLog(@"%@",fullName);

        

/////////////////////////////////////////////////////////////////////////

        

        //获取通讯录联系人的电话号码(多值)和电子邮件(多值)

        ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue((__bridgeABRecordRef)(person), kABPersonPhoneProperty);

        

        for (int i = 0; i < ABMultiValueGetCount(phones); i++) {

            NSString *phone = (__bridgeNSString*)ABMultiValueCopyValueAtIndex(phones, i);

            NSLog(@"phone number is %@",phone);

        }

        

        ABMultiValueRef mails = (ABMultiValueRef)ABRecordCopyValue((__bridgeABRecordRef)(person), kABPersonEmailProperty);

        for (int i = 0; i < ABMultiValueGetCount(mails); i++) {

            NSString *mail = (__bridgeNSString*)ABMultiValueCopyValueAtIndex(mails, i);

            NSLog(@"email is %@",mail);

        }

        

    }

/////////////////////////////////////////////////////////////////////////

    

    if (allPeople) {

        CFRelease(allPeople);

    }

    

    if (addressBook) {

        CFRelease(addressBook);

    }

}


    //2、添加联系人信息

-(void)addContact:(Contact *)contact addressBookRef:(ABAddressBookRef)addrBookRef{

    

    ABRecordRef person = ABPersonCreate();

    

    ABRecordSetValue(person, kABPersonFirstNameProperty, (__bridgeCFTypeRef)(contact.firstName), NULL);

    ABRecordSetValue(person, kABPersonLastNameProperty, (__bridgeCFTypeRef)(contact.lastName), NULL);

    

    ABMutableMultiValueRef mulRef = ABMultiValueCreateMutable(kABMultiStringPropertyType);

    for (int i = 0; i < contact.phoneArray.count; i++) {

        ABMultiValueIdentifier multivalueIdentifier;

        ABMultiValueAddValueAndLabel(mulRef, (__bridge CFTypeRef)([contact.phoneArray objectAtIndex:i]), nil, &multivalueIdentifier);

    }

    ABRecordSetValue(person, kABPersonPhoneProperty, mulRef, NULL);

    if (mulRef) {

        CFRelease(mulRef);

    }

    

    if ([contact mail] != nil && ![contact.mail isEqualToString:@""]) {

        ABMutableMultiValueRef mulRef3 = ABMultiValueCreateMutable(kABMultiStringPropertyType);

        ABMultiValueIdentifier multivalueIdentifier;

        ABMultiValueAddValueAndLabel(mulRef3, (__bridge CFTypeRef)(contact.mail), nil, &multivalueIdentifier);

        ABRecordSetValue(person, kABPersonEmailProperty, mulRef3, NULL);

        if (mulRef3) {

            CFRelease(mulRef3);

        }

    }

    

    ABAddressBookAddRecord(addrBookRef, person, NULL);

    

    if (person) {

        CFRelease(person);

    }

    ABAddressBookSave(addrBookRef, nil);//保存对通讯录的修改(重点),如需要添加多条联系人信息,将该行代码放到添加联系人信息的循环之后,执行速度比每添加一条联系人信息就保存一次对通讯录的修改要快很多

}


//3、删除联系人信息

-(void)deleteContact:(NSString *)fullName addressBookRef:(ABAddressBookRef)addrBookRef{

    

    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addrBookRef);

    

    NSString *firstName, *lastName;

    for (id person in (__bridge NSArray*)allPeople) {

        

        firstName = (__bridgeNSString*)ABRecordCopyValue((__bridgeABRecordRef)(person), kABPersonFirstNameProperty);

        if (firstName == nil) {

            firstName = @"";

        }

        

        lastName = (__bridgeNSString*)ABRecordCopyValue((__bridgeABRecordRef)(person), kABPersonLastNameProperty);

        if (lastName == nil) {

            lastName = @"";

        }

        

        if ([fullName isEqualToString:[lastName stringByAppendingFormat:@"%@",firstName]]) {

            ABAddressBookRemoveRecord(addrBookRef, (__bridge ABRecordRef)(person), NULL);

            break;

        }

    }

    

    if (allPeople) {

        CFRelease(allPeople);

    }

    ABAddressBookSave(addrBookRef, nil);//保存对通讯录的修改(重点),如需要删除多条联系人信息,将该行代码放到删除联系人信息的循环之后,执行速度比每删除一条联系人信息就保存一次对通讯录的修改要快很多

}


#pragma mark peoplePickerDelegate

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker

{

    [selfdismissViewControllerAnimated:YEScompletion:^{}];

}


- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person

{

    returnYES;

}


- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker

      shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

    NSString* compositeName = (__bridgeNSString *)ABRecordCopyCompositeName(person);

    ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);

    NSString *phone = (__bridge NSString *)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);

    _phoneNumTextField.text= (NSString*)phone;

    [selfdismissViewControllerAnimated:YEScompletion:^{}];

    returnNO;

}


- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end

 

 

posted @ 2014-07-29 17:56  WongBob  阅读(196)  评论(0编辑  收藏  举报