iOS開發之系統通訊錄

                      @iOS調用操作通訊錄所用的庫文件

                                        AddressBook.framework

                                        AddressBookUI.framework

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

@interface HMTMainViewController ()<ABPeoplePickerNavigationControllerDelegate>

@property (nonatomic,strong) ABPeoplePickerNavigationController *personPickVC;
@property (nonatomic,strong) UIWebView *phoneCallWebView;

@end

@implementation HMTMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"系統通訊錄";
    
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"刪除" style:UIBarButtonItemStylePlain target:self action:@selector(didClickDeletePersonAction)];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 70, 120, 40);
    [button setTitle:@"選擇聯繫人" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didClickSelectAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
}


- (void)didClickSelectAction{
    
    //  選擇電話薄的聯繫人
    self.personPickVC = [[ABPeoplePickerNavigationController alloc] init];
    _personPickVC.peoplePickerDelegate = self;
    _personPickVC.displayedProperties = @[[NSNumber numberWithInt:kABPersonPhoneProperty]];
    [self deletePerson];
    [self presentViewController:_personPickVC animated:YES completion:NULL];
    //[self.navigationController pushViewController:[_personPickVC.viewControllers objectAtIndex:0] animated:YES];
    //[self getAllPerson];
    
    
    
}

//  進入選擇聯繫人界面
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{

    //  選中聯繫人後,就退出,並返回想要的屬性
    [peoplePicker dismissViewControllerAnimated:YES completion:^{
       
        NSString *firstName = (__bridge NSString*)ABRecordCopyValue(person, kABPersonFirstNameProperty);
        NSLog(@"person = %@",firstName);
        
        ABMultiValueRef phones = ABRecordCopyValue(person,kABPersonPhoneProperty);
        for (int i = 0; i < ABMultiValueGetCount(phones); i++) {
            NSString *phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, i));
            NSLog(@"telephone = %@",phone);
        }
    }];
    
    return YES;
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{

    [peoplePicker dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{

    return YES;
}

//  展示所有聯繫人
- (void)getAllPerson{

    CFArrayRef allPerson = ABAddressBookCopyArrayOfAllPeople(self.personPickVC.addressBook);
    for (id person in ((__bridge NSArray *)allPerson)) {
        
        NSString *firstName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonFirstNameProperty);
        NSLog(@"firstName = %@",firstName);
 
        //  因爲一個用戶可能有多個電話,所以需要循環調取
        ABMultiValueRef phones = ABRecordCopyValue((__bridge ABRecordRef)person,kABPersonPhoneProperty);
        for (int i = 0; i < ABMultiValueGetCount(phones); i++) {
            NSString *phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, i));
            NSLog(@"telephone = %@",phone);
        }
        
    }
}

//  添加聯繫人
- (void)addPerson{

    ABAddressBookRef addressBook = self.personPickVC.addressBook;
    ABRecordRef person = ABPersonCreate();
    ABRecordSetValue(person, kABPersonFirstNameProperty, @"胡", nil);
    ABRecordSetValue(person, kABPersonLastNameProperty, @"明濤", nil);
    ABMutableMultiValueRef mulRef = ABMultiValueCreateMutable(kABStringPropertyType);
    for (int i = 0; i < 1; i++) {
        ABMultiValueIdentifier mutableIdentifier;
        ABMultiValueAddValueAndLabel(mulRef, @"18690231234", nil, &mutableIdentifier);
    }
    ABRecordSetValue(person, kABPersonPhoneProperty, mulRef, nil);
    ABAddressBookAddRecord(addressBook, person, nil);
    ABAddressBookSave(addressBook, nil);
    
}

//  刪除聯繫人
- (void)deletePerson{
    
    CFArrayRef allPerson = ABAddressBookCopyArrayOfAllPeople(self.personPickVC.addressBook);
    for (id person in (__bridge NSArray *)allPerson) {
        
        NSString *firstName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)person, kABPersonFirstNameProperty);
        if ([firstName isEqualToString:@"胡"]) {
            ABAddressBookRemoveRecord(self.personPickVC.addressBook, (__bridge ABRecordRef)person, nil);
        }
    }
    ABAddressBookSave(self.personPickVC.addressBook, nil);
}

//  撥打電話
- (void)dialPhoneNumber:(NSString *)phoneNumber{

    // 1.UIWebView加載電話
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNumber]];
    self.phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
    [self.phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
    
    // 2.私有方法
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://10086"]];
}


@有的時候,我們按上訴方法訪問通訊錄無效,這是因爲,iOS6之後加強了對通訊錄的訪問,要求我們顯示的申請去訪問通訊錄,加上如下幾句代碼就OK了:

    CFErrorRef *error = nil;
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    // Request authorization to Address Book
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                if (granted) {
                    // First time access has been granted, add the contact
                    //[self _addContactToAddressBook];
                } else {
                    // User denied access
                    // Display an alert telling user the contact could not be added
                }
            });
        }
        else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized) {
            // The user has previously given access, add the contact
            //[self _addContactToAddressBook];
        }
        else {
            // The user has previously denied access
            // Send an alert telling user to change privacy setting in settings app
    }



發佈了169 篇原創文章 · 獲贊 13 · 訪問量 87萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章