首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 判斷 App 是否開啟推送通知權限的標準 API:enabledRemoteNotificationTypes

     編輯:程式設計綜合問答

標準檢查代碼


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適用版本回調方式信息豐富度
enabledRemoteNotificationTypesiOS 3-9 (Deprecated 10.0)同步返回僅類型位掩碼
UNUserNotificationCenter.getNotificationSettingsiOS 10+異步回調授權狀態、各類型開關、關鍵提醒、預覽設置等

最佳實踐

  • 新項目**直接使用 UserNotifications 框架**,棄用舊 API。
  • 異步回調中更新 UI/邏輯,避免主線程阻塞。
  • 若需引導用戶開啟權限,提供「去設置」按鈕跳轉 UIApplicationOpenSettingsURLString。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved