在 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 決定後續行為
});
}];
}
這類帳號由 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 */ }
});
});
}
NSCameraUsageDescription),否則新版系統會直接讓 App 崩潰。