如何在程序中检测 iOS 推送通知的权限/设置

4
在通知设置(设置->通知->任何应用名称)中,有5个项目,每个项目都有一个开关按钮“声音”,“应用图标徽章”,“在锁定屏幕上显示”,“在历史记录中显示”和“作为横幅显示”。
我正在使用[[[UIApplication sharedApplication] currentUserNotificationSettings] types]获取用户的设置并提供相应的警报以使用。它可能返回值0~7,代表声音徽章横幅的任意组合。问题是,我们能否检测到在锁定屏幕上显示在历史记录中显示的状态?
此外,在设置页面底部,有一个名为OPTIONS的选项,称为显示预览,它有三个选项:始终(默认)解锁时从不。我们能否编程获取用户对此的设置?
1个回答

1
你应该使用UserNotifications框架,该框架从iOS 10开始支持。这将允许你通过UNUserNotificationCenter的getNotificationSettingsWithCompletionHandler:函数检索UNNotificationSettings。在UNNotificationSettings中,你可以检查一些值:
- notificationCenterSetting(“在历史记录中显示”) - lockScreenSetting(“在锁定屏幕上显示”) - alertSetting(“作为横幅显示”) - alertStyle(横幅的类型)
例如:
[[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
    if(settings.authorizationStatus == UNAuthorizationStatusAuthorized) {
        //notifications are enabled for this app

        if(settings.notificationCenterSetting == UNNotificationSettingEnabled ||
          settings.lockScreenSetting == UNNotificationSettingEnabled ||
          (settings.alertSetting == UNNotificationSettingEnabled && settings.alertStyle != UNAlertStyleNone)) {
            //the user will be able to see the notifications (on the lock screen, in history and/or via banners)

            dispatch_async(dispatch_get_main_queue(), ^(){

                //now for instance, register for remote notifications
                //execute this from the main queue
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            });
        }
        else {
            //the user must change notification settings in order te receive notifications
        }
    }
    else {
        //request authorization
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if(granted) {
                dispatch_async(dispatch_get_main_queue(), ^(){

                    //now for instance, register for remote notifications
                    //execute this from the main queue
                    [[UIApplication sharedApplication] registerForRemoteNotifications];
                });
            }
            else {
                //user denied the authorization request
                //the user must change notification settings in order te receive notifications
            }
        }
    }
}];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接