你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS7中讀取通訊錄信息授權問題

iOS7中讀取通訊錄信息授權問題

編輯:IOS開發綜合

大家知道在讀取通訊錄信息時需要引用AddressBook、AddressBookUI得框架,然後就可以進行相關操作。但是在iOS7中不能夠像iOS6中直接讀取通訊錄信息,而是需要代碼中取得用戶授權才可以進行相關操作。

推薦使用如下方式:

CFErrorRef *error = nil;
    
    
        ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
    
        __block BOOL accessGranted = NO;
        if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
            dispatch_semaphore_t sema = dispatch_semaphore_create(0);
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                accessGranted = granted;
                dispatch_semaphore_signal(sema);
        });
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
        }
        else { // we're on iOS 5 or older
           accessGranted = YES;
       }

if (accessGranted) {

NSMutableArray *addressBookTemp = [NSMutableArray array];

//ABAddressBookRef addressBooks = ABAddressBookCreate();

CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);

CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);

for (NSInteger i = 0; i < nPeople; i++)

{

TKAddressBook *addressBook = [[TKAddressBook alloc] init];

ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i);

CFStringRef abName = ABRecordCopyValue(person, kABPersonFirstNameProperty);

CFStringRef abLastName = ABRecordCopyValue(person, kABPersonLastNameProperty);

CFStringRef abFullName = ABRecordCopyCompositeName(person);

}

...................................

}
另外,網上還有一種版本

//    CFErrorRef *error = nil;
//    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
//    
//    __block BOOL accessGranted = NO;
//    
//    if (ABAddressBookGetAuthorizationStatus()==kABAuthorizationStatusNotDetermined){
//        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
//            
//            accessGranted=granted;
//        });
//        
//    }
//    else if (ABAddressBookGetAuthorizationStatus()==kABAuthorizationStatusAuthorized){
//        accessGranted=YES;
//    }
//    else
//    {
//        NSLog(@"用戶未授權提示");
//    }
    
不推薦後者得原因是:經過測試(模擬器)後者取得用戶授權後並不能立刻執行獲取聯系人等得相關操作,而前者可以順利執行。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved