在iPhone上确定用户是否启用了推送通知

211

我正在寻找一种方法来确定用户是否通过设置启用或禁用了我的应用程序的推送通知。

19个回答

5

对于iOS7及以下版本,您确实应该使用enabledRemoteNotificationTypes并检查它是否等于(或不等于,这取决于您的需求)UIRemoteNotificationTypeNone

但是对于iOS8,并不总是仅通过检查isRegisteredForRemoteNotifications就足够了,正如许多人所述。您还应该检查application.currentUserNotificationSettings.types是否等于(或不等于,这取决于您的需求)UIUserNotificationTypeNone

isRegisteredForRemoteNotifications可能会返回true,即使currentUserNotificationSettings.types返回UIUserNotificationTypeNone


4

我尝试使用@Shaheen Ghiassy提供的解决方案支持iOS 10及以上版本,但发现了enabledRemoteNotificationTypes的剥夺问题。因此,我使用isRegisteredForRemoteNotifications替代了enabledRemoteNotificationTypes,后者在iOS 8中已经过时。下面是我的更新解决方案,对我完美地起作用:

- (BOOL)notificationServicesEnabled {
    BOOL isEnabled = NO;
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]){
        UIUserNotificationSettings *notificationSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];

        if (!notificationSettings || (notificationSettings.types == UIUserNotificationTypeNone)) {
            isEnabled = NO;
        } else {
            isEnabled = YES;
        }
    } else {

        if ([[UIApplication sharedApplication] isRegisteredForRemoteNotifications]) {
            isEnabled = YES;
        } else{
            isEnabled = NO;
        }
    }
    return isEnabled;
}

我们可以轻松地调用此函数并访问其Bool值,并通过以下方式将其转换为字符串值:

NSString *str = [self notificationServicesEnabled] ? @"YES" : @"NO";

希望这也能帮助其他人 :) 愉快编码。


4
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types & UIRemoteNotificationTypeAlert)
    // blah blah blah
{
    NSLog(@"Notification Enabled");
}
else
{
    NSLog(@"Notification not enabled");
}

在这里,我们从UIApplication获取UIRemoteNotificationType。它代表了此应用程序在设置中的推送通知状态,您可以轻松地检查其类型。


3
请解释这段代码的作用,编写代码并不足以回答问题。请说明此代码的功能,编写代码不能简单地回答此问题。 - codingenious

3

虽然 Zac 的回答在 iOS 7 之前是完全正确的,但自从 iOS 8 推出以来就发生了改变。因为从 iOS 8 开始,enabledRemoteNotificationTypes 已被弃用。对于 iOS 8 及更高版本,您需要使用 isRegisteredForRemoteNotifications

  • iOS 7 及之前版本 --> 使用 enabledRemoteNotificationTypes
  • iOS 8 及之后版本 --> 使用 isRegisteredForRemoteNotifications。

2
This Swifty解决方案在iOS8+上对我非常有效。
方法:
func isNotificationEnabled(completion:@escaping (_ enabled:Bool)->()){
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
            let status =  (settings.authorizationStatus == .authorized)
            completion(status)
        })
    } else {
        if let status = UIApplication.shared.currentUserNotificationSettings?.types{
            let status = status.rawValue != UIUserNotificationType(rawValue: 0).rawValue
            completion(status)
        }else{
            completion(false)
        }
    }
}

用法:

isNotificationEnabled { (isEnabled) in
            if isEnabled{
                print("Push notification enabled")
            }else{
                print("Push notification not enabled")
            }
        }

Ref


0
在 Xamarin 中,以上所有的解决方案对我都不起作用。 以下是我使用的:
public static bool IsRemoteNotificationsEnabled() {
    return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}

在设置中更改通知状态后,它也会进行实时更新。


0

以下是在Xamarin.ios中执行此操作的方法。

public class NotificationUtils
{
    public static bool AreNotificationsEnabled ()
    {
        var settings = UIApplication.SharedApplication.CurrentUserNotificationSettings;
        var types = settings.Types;
        return types != UIUserNotificationType.None;
    }
}

如果你只支持iOS 10及以上版本,那就选择使用UNUserNotificationCenter方法。

0

回复:

这是正确的

if (types & UIRemoteNotificationTypeAlert)

但是以下写法也是正确的!(因为UIRemoteNotificationTypeNone等于0)

if (types == UIRemoteNotificationTypeNone) 

请看下面。
NSLog(@"log:%d",0 & 0); ///false
NSLog(@"log:%d",1 & 1); ///true
NSLog(@"log:%d",1<<1 & 1<<1); ///true
NSLog(@"log:%d",1<<2 & 1<<2); ///true
NSLog(@"log:%d",(0 & 0) && YES); ///false
NSLog(@"log:%d",(1 & 1) && YES); ///true
NSLog(@"log:%d",(1<<1 & 1<<1) && YES); ///true
NSLog(@"log:%d",(1<<2 & 1<<2) && YES); ///true

-1

完整的易于复制和粘贴的代码,基于@ZacBowling的解决方案构建(https://dev59.com/AHI_5IYBdhLWcg3wEe5u#1535427

这也将带用户到您的应用程序设置,并允许他们立即启用

我还添加了一个检查位置服务是否已启用的解决方案(并将其带到设置中)

// check if notification service is enabled
+ (void)checkNotificationServicesEnabled
{
    if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification Services Disabled!"
                                                            message:@"Yo don't mess around bro! Enabling your Notifications allows you to receive important updates"
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];

        alertView.tag = 300;

        [alertView show];

        return;
    }
}

// check if location service is enabled (ref: https://dev59.com/zGUp5IYBdhLWcg3woonS#35982887)
+ (void)checkLocationServicesEnabled
{
    //Checking authorization status
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
    {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!"
                                                            message:@"You need to enable your GPS location right now!!"
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];

        //TODO if user has not given permission to device
        if (![CLLocationManager locationServicesEnabled])
        {
            alertView.tag = 100;
        }
        //TODO if user has not given permission to particular app
        else
        {
            alertView.tag = 200;
        }

        [alertView show];

        return;
    }
}

// handle bringing user to settings for each
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if(buttonIndex == 0)// Cancel button pressed
    {
        //TODO for cancel
    }
    else if(buttonIndex == 1)// Settings button pressed.
    {
        if (alertView.tag == 100)
        {
            //This will open ios devices location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
        }
        else if (alertView.tag == 200)
        {
            //This will open particular app location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
        else if (alertView.tag == 300)
        {
            //This will open particular app location settings
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}

祝你好运!


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