iOS通信錄

1.添加或刪除通訊錄,無需跳轉到通信錄界面數組

/** 添加通信錄 */
+ (void)requestAddRLNumIntoContact
{
    if ([self isExistContactRLNum]) {
        debugLog(@"聯繫人已存在");
    }else{
        [self createRLNum];
    }
}

/**訪問通信錄而且檢查是否聯繫已存在*/
+ (BOOL)isExistContactRLNum
{
    //記錄用戶是否容許咱們訪問通信錄
    int __block tip = 0;
    BOOL __block isExist = NO;
    
    //聲明通信簿
    ABAddressBookRef addBook = nil;
    
    //受權
    CFErrorRef error = NULL;
    addBook = ABAddressBookCreateWithOptions(NULL, &error);
    
    //建立初始信號量爲0的信號,實現NSOperation的依賴關係
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
    //申請訪問權限
    ABAddressBookRequestAccessWithCompletion(addBook, ^(bool granted, CFErrorRef error) {
        if (!granted) {//用戶不容許
            tip=1;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                popAlertView *popView = [[popAlertView alloc] initWithNib:[UIImage imageNamed:@"smart_success_"] tipsLabStr:@"是否容許請求訪問你的通信錄" tipsBtnStr:@"肯定"];
                [popView.showBtn addTarget:self action:@selector(ensurePushContacts) forControlEvents:UIControlEventTouchUpInside];
                [popView show];
                
            });
            
        }else{
            //獲取聯繫人的數組
            CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
            //獲取聯繫人總數
            CFIndex number = ABAddressBookGetPersonCount(addBook);
            //進行遍歷
            for (NSInteger i = 0; i < number; i++) {
                //獲取單個聯繫人對象
                ABRecordRef people = CFArrayGetValueAtIndex(allLinkPeople, i);
                //獲取聯繫人名字
                NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
                if ([firstName isEqualToString:@"智慧辦公"]) {
                    isExist = YES;
                }
            }
            
        }
        
        if (tip) {
            dispatch_async(dispatch_get_main_queue(), ^{
                popAlertView *popView = [[popAlertView alloc] initWithNib:[UIImage imageNamed:@"smart_success_"] tipsLabStr:@"是否容許請求訪問你的通信錄" tipsBtnStr:@"肯定"];
                [popView.showBtn addTarget:self action:@selector(ensurePushContacts) forControlEvents:UIControlEventTouchUpInside];
                [popView show];
                
            });
            
            isExist = YES;
        }
        
        //發送一次信號
        dispatch_semaphore_signal(sema);
        
    });
    //等待信號觸發
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    return isExist;
}

/**添加通信錄*/
+ (void)createRLNum
{
    CFErrorRef error = NULL;
    
    //建立一個通信錄操做對象
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    
    //建立一條新的聯繫人記錄
    ABRecordRef newRecord = ABPersonCreate();
    
    //爲新聯繫人記錄添加屬性值
    ABRecordSetValue(newRecord, kABPersonFirstNameProperty, (__bridge CFTypeRef)(@"智慧辦公"), &error);
    
    //建立一個多值屬性(電話)
    ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABMultiStringPropertyType);
    ABMultiValueAddValueAndLabel(multi, (__bridge CFTypeRef)(@"02096911328"), kABPersonPhoneMobileLabel, NULL);
    ABRecordSetValue(newRecord, kABPersonPhoneProperty, multi, &error);
    
    //添加記錄到通信錄操做對象
    ABAddressBookAddRecord(addressBook, newRecord, &error);
    
    //保存通信錄操做對象
    ABAddressBookSave(addressBook, &error);
    
    
    //經過此接口訪問系統通信錄
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted) {
            debugLog(@"添加聯繫人成功");
        }
    });
    
    CFRelease(multi);
    CFRelease(newRecord);
    CFRelease(addressBook);
}

/**清空通信錄*/
+(void)deleteContacts
{
    CFErrorRef error = NULL;
    
    //建立一個通信錄操做對象
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &error);
    
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        if (granted && !error) {
            CFArrayRef personArray = ABAddressBookCopyArrayOfAllPeople(addressBook);
            CFIndex personCount = ABAddressBookGetPersonCount(addressBook);
            
            if (personCount <= 0) {
                return;
            }
            
            for (int i = 0; i < personCount; i++) {
                ABRecordRef ref = CFArrayGetValueAtIndex(personArray, i);
                // 刪除聯繫人
                ABAddressBookRemoveRecord(addressBook, ref, nil);
            }
            
            // 保存通信錄操做對象
            ABAddressBookSave(addressBook, &error);
            CFRelease(addressBook);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!error) {
                } else {
                }
            });
        }
    });
}

+ (void)ensurePushContacts
{
    NSString *string = @"prefs:root=Privacy&path=CONTACTS";
    NSURL *url = [NSURL URLWithString:string];
    [[UIApplication sharedApplication] openURL:url];
}

 

2.獲取點擊選擇的通訊人名字和電話async

//
//  ViewController.m
//  WWW
//
//  Created by ling on 16/8/16.
//  Copyright © 2016年 ldccomputer. All rights reserved.
//

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

@interface ViewController ()<ABPeoplePickerNavigationControllerDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
    peoplePicker.peoplePickerDelegate = self;
    [self authoriy];
    [self presentViewController:peoplePicker animated:YES completion:nil];
}



/**
 *  受權註冊
 */

- (void)authoriy{
    if (&ABAddressBookRequestAccessWithCompletion != NULL) {
        //iOS6
        ABAddressBookRef abRef = ABAddressBookCreateWithOptions(NULL, NULL);
        if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined) {
            //若是沒申請過權限,申請權限
            ABAddressBookRequestAccessWithCompletion(abRef, ^(bool granted, CFErrorRef error) {
                if (granted) { //granted表明是否贊成授予權限
                    //查詢通信錄全部聯繫人
                    [self getContacts];
                }
            });
        }else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
            //權限已經授予
            [self getContacts];
        }else{
            //權限不被授予
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"舒適提示" message:@"請您設置容許APP訪問您的通信錄\n設置>通用>訪問權限" delegate:self cancelButtonTitle:@"" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        if (abRef) {
            CFRelease(abRef);
        }
        
    }
}

/**
 *  獲取通信錄全部聯繫人
 */
- (void)getContacts{
    //獲取全部通信錄單元信息
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    
    //取所有聯繫人
    CFArrayRef allPerson = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex number = ABAddressBookGetPersonCount(addressBook);
    
    //遍歷
    for (NSInteger i = 0; i < number; i++) {
        ABRecordRef people = CFArrayGetValueAtIndex(allPerson, i);
        
        //聯繫人的姓名
        NSString *firstName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonFirstNameProperty);
        NSString *middleName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonMiddleNameProperty);
        NSString *lastName = (__bridge NSString *)ABRecordCopyValue(people, kABPersonLastNameProperty);
        
        NSString *nameString = [NSString stringWithFormat:@"%@%@%@",firstName,middleName,lastName];
    //    NSLog(@"name : %@",nameString);
        
        //聯繫人電話
        ABMutableMultiValueRef phoneMutil = ABRecordCopyValue(people, kABPersonPhoneProperty);
        NSMutableArray *phones = [NSMutableArray array];
        
        for (int i = 0; i < ABMultiValueGetCount(phoneMutil); i ++) {
            
            NSString *phoneLabel = (__bridge NSString *)ABMultiValueCopyLabelAtIndex(phoneMutil, i);
#warning _$!<Mobile>!$_取出固話和電話號碼,但400開頭的沒法獲取
            if ([phoneLabel isEqualToString:@"_$!<Mobile>!$_"]) {
                [phones addObject:(__bridge id _Nonnull)(ABMultiValueCopyValueAtIndex(phoneMutil, i))];
            }
            
        }
//        NSLog(@"phone:%@",phones);
        
    }
}

/**
 *  選擇後的代理
 */
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef, identifier);
    CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef, index);
    
    CFStringRef anFullName = ABRecordCopyCompositeName(person);
    
    [peoplePicker dismissViewControllerAnimated:YES completion:^{
        [self dismissViewControllerAnimated:YES completion:^{
            self.contactPhoneNumber  = (__bridge NSString *)(value);
            self.contactName         = (__bridge NSString *)(anFullName);
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Num" object:self.contactPhoneNumber userInfo: @{@"name" : self.contactName}];
            
        }];
    }];
    
    self.contactPhoneNumber  = (__bridge NSString *)(value);
    self.contactName         = (__bridge NSString *)(anFullName);
    NSLog(@" notif1 :%@ %@",self.contactPhoneNumber,self.contactName);
}



-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
相關文章
相關標籤/搜索