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


当前回答

在最新版本的iOS中,这种方法已被弃用。支持iOS 7和iOS 8使用:

UIApplication *application = [UIApplication sharedApplication];

BOOL enabled;

// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
    enabled = [application isRegisteredForRemoteNotifications];
}
else
{
    UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
    enabled = types & UIRemoteNotificationTypeAlert;
}

其他回答

在最新版本的iOS中,这种方法已被弃用。支持iOS 7和iOS 8使用:

UIApplication *application = [UIApplication sharedApplication];

BOOL enabled;

// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
    enabled = [application isRegisteredForRemoteNotifications];
}
else
{
    UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
    enabled = types & UIRemoteNotificationTypeAlert;
}

调用enabledremotenotificationsttypes并检查掩码。

例如:

UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone) 
   // blah blah blah

iOS8及以上:

[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]

在Xamarin,以上所有的解决方案都不适合我。 这是我用的:

public static bool IsRemoteNotificationsEnabled() {
    return UIApplication.SharedApplication.CurrentUserNotificationSettings.Types != UIUserNotificationType.None;
}

当你在设置中更改通知状态后,它也会得到实时更新。

尽管Zac的答案在iOS 7之前是完全正确的,但自从iOS 8到来后,它就发生了变化。因为enabledRemoteNotificationTypes从iOS 8开始就已经弃用了。对于iOS 8和更高版本,你需要使用isregisteredforremotenotifizations。

—>使用enabledRemoteNotificationTypes >使用isregisteredforremotenotifizations。

在iOS7和之前,你应该使用enabledRemoteNotificationTypes并检查它是否等于(或不等于取决于你想要什么)UIRemoteNotificationTypeNone。

然而,对于iOS8来说,仅仅检查isregisteredforremotenotifations并不总是足够的,因为上面有许多状态。你还应该检查application.currentUserNotificationSettings.types是否等于(或不等于取决于你想要什么)UIUserNotificationTypeNone!

isregisteredforremotenotifations可能返回true,即使currentUserNotificationSettings。types返回UIUserNotificationTypeNone。