您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 權限申請實戰:錄音、行事曆、社群帳號與通訊錄一次搞定

編輯:iOS 開發綜合

在 iOS 上,凡是涉及使用者隱私或系統資源的功能,都必須先取得授權。早期只要呼叫 API 就能存取,但從 iOS 6 開始,Apple 逐步把相簿、聯絡人、行事曆、麥克風、社群帳號等資源都納入「先詢問、後存取」的機制。以下把幾個最常見的權限申請寫法整理在一起,方便日後查閱。

一、麥克風(錄音)權限

錄音相關的授權由 AVAudioSession 負責,只要呼叫 requestRecordPermission: 就會跳出系統提示框。

-(void)requestRecord{
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // granted 為 YES 代表使用者已同意
        });
    }];
}

二、行事曆與提醒事項權限

事件庫需要透過 EKEventStore 存取,並以 EKEntityType 區分是「行事曆」還是「提醒事項」。

-(void)requestAccessEventWithType:(EKEntityType)eventType{
    [[EKEventStore new] requestAccessToEntityType:eventType completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 依 granted 決定後續行為
        });
    }];
}

三、社群帳號權限(Twitter、Facebook 等)

這類帳號由 ACAccountStore 管理,透過「帳號類型識別字串」指定要申請哪一種服務。

- (void)requestAccessSocial:(NSString*)identifer{
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *twAccountType = [accountStore accountTypeWithAccountTypeIdentifier:identifer];
    [accountStore requestAccessToAccountsWithType:twAccountType options:nil completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 取得帳號陣列後即可發送貼文
        });
    }];
}

四、通訊錄權限

iOS 6 之後必須改用 ABAddressBookCreateWithOptions 建立聯絡簿,再呼叫 ABAddressBookRequestAccessWithCompletion 等待授權結果。

-(void)AddressBookRequest{
    ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (grured) { /* TODO */ }
        });
    });
}

幾個實務上的提醒

  • 所有回呼(completion)都可能不在主執行緒,更新 UI 前務必切回 main queue。
  • 除了主畫面的提示框,也建議在 Info.plist 中補上各項用途說明字串(如 NSCameraUsageDescription),否則新版系統會直接讓 App 崩潰。
  • 使用者一旦拒絕,系統不會再重複彈出提示,此時只能引導使用者到「設定」中手動開啟,因此記得先查詢授權狀態再決定要不要發送請求。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved