IOS——通訊錄操作(適用於IOS6)

人醜就該多讀書發表於2013-06-06

      馬上就要開始新的專案了,由於原型和UI還沒有到位,趁著空閒的時間很多,就提前做了一些驗證性的工作,做完就立馬來mark一下,這次說的通訊錄


在IOS5之前,訪問通訊錄只需要加入簡單的程式碼就可以進行操作,程式碼如下:


ABAddressBookRef addressBook = ABAddressBookCreate();

不過,在IOS6上面已經不是這樣子了,由於之前的IOS版本在隱私方面被人詬病,現在每個APP要訪問通訊錄都需要得到使用者的授權。(當然,漢化的比較坑爹,居然提示說要訪問日曆,而不是通訊錄,可能外國人認為中國人的日曆就是通訊錄吧)

程式碼如下:

     ABAddressBookRef addressBook = nil;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        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);
        dispatch_release(sema);
    }
    else
    {
        addressBook = ABAddressBookCreate();
    }
呼叫上面的程式碼,就可以適配IOS6和IOS5了,不過,這隻會在第一次請求授權的時才會顯示對話方塊,如果使用者已經拒絕,那麼只好我們自己判斷授權狀態了。程式碼:

NSLog(@"%ld",ABAddressBookGetAuthorizationStatus());
這樣就可以知道授權狀態了,另外附上官方的解釋:

// To check the app's access to contact data. Based upon the access, the app could
// display or hide its UI elements that would access any AddressBook API.
//
// kABAuthorizationStatusNotDetermined
// The user has not yet made a choice regarding whether this app can access the data class.
//
// kABAuthorizationStatusRestricted
// This application is not authorized to access the data class. The user cannot change
// this application’s status, possibly due to active restrictions such as parental controls
// being in place.
//
// kABAuthorizationStatusDenied
// The user explicitly denied access to the data class for this application.
//
// kABAuthorizationStatusAuthorized
// This application is authorized to access the data class.
//
typedef CF_ENUM(CFIndex, ABAuthorizationStatus) {
    kABAuthorizationStatusNotDetermined = 0,
    kABAuthorizationStatusRestricted,
    kABAuthorizationStatusDenied,
    kABAuthorizationStatusAuthorized
};
AB_EXTERN ABAuthorizationStatus ABAddressBookGetAuthorizationStatus(void) __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_6_0);

知道了授權狀態,我們就可以提醒使用者去設定裡面改變授權授權狀態了。


程式安裝之後,只有第一次會提示是否訪問通訊錄,第二次就不會了,即使刪除了程式,也是不會重現的,非常不方便大家除錯,其實,裝置還原之後,它還是會出現的。

還原步驟:設定-通用-還原-還原位置與隱私

相關文章