標準檢查代碼
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone) {
// 用戶未授權任何推送類型(彈窗、聲音、角標)
NSLog(@"推送通知權限未開啟");
} else {
// 權限已開啟,可檢查具體類型
BOOL hasAlert = types & UIRemoteNotificationTypeAlert;
BOOL hasSound = types & UIRemoteNotificationTypeSound;
BOOL hasBadge = types & UIRemoteNotificationTypeBadge;
}
iOS 10+ 現代 API (UserNotifications 框架)
#import
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {
switch (settings.authorizationStatus) {
case UNAuthorizationStatusAuthorized:
NSLog(@"已授權");
break;
case UNAuthorizationStatusDenied:
NSLog(@"用戶拒絕");
break;
case UNAuthorizationStatusNotDetermined:
NSLog(@"未詢問");
break;
case UNAuthorizationStatusProvisional:
case UNAuthorizationStatusEphemeral:
// 特殊臨時授權
break;
}
// 具體類型
BOOL hasAlert = settings.alertSetting == UNNotificationSettingEnabled;
BOOL hasSound = settings.soundSetting == UNNotificationSettingEnabled;
BOOL hasBadge = settings.badgeSetting == UNNotificationSettingEnabled;
}];
Swift 版本
UNUserNotificationCenter.current().getNotificationSettings { settings in
switch settings.authorizationStatus {
case .authorized: print("已授權")
case .denied: print("已拒絕")
case .notDetermined: print("未詢問")
@unknown default: break
}
// 彈窗/聲音/角標單獨檢查
let hasAlert = settings.alertSetting == .enabled
}
關鍵差異
| API | 適用版本 | 回調方式 | 信息豐富度 |
enabledRemoteNotificationTypes | iOS 3-9 (Deprecated 10.0) | 同步返回 | 僅類型位掩碼 |
UNUserNotificationCenter.getNotificationSettings | iOS 10+ | 異步回調 | 授權狀態、各類型開關、關鍵提醒、預覽設置等 |
最佳實踐
- 新項目**直接使用 UserNotifications 框架**,棄用舊 API。
- 異步回調中更新 UI/邏輯,避免主線程阻塞。
- 若需引導用戶開啟權限,提供「去設置」按鈕跳轉
UIApplicationOpenSettingsURLString。