Ios 在应用程序设置中实现切换以切换通知
我正在尝试在我的应用程序的本地设置SVC中实现一个开关,以打开/关闭通知。我现在决定让用户在服务器上注册(APNS和AppBoy),只需打开/关闭通知的本地显示 (如果用户以前注册过。如果他们从未注册过,此代码应在他们第一次切换到“开”时注册) 以下是用户扳动开关时的代码:Ios 在应用程序设置中实现切换以切换通知,ios,swift,notifications,Ios,Swift,Notifications,我正在尝试在我的应用程序的本地设置SVC中实现一个开关,以打开/关闭通知。我现在决定让用户在服务器上注册(APNS和AppBoy),只需打开/关闭通知的本地显示 (如果用户以前注册过。如果他们从未注册过,此代码应在他们第一次切换到“开”时注册) 以下是用户扳动开关时的代码: func didFlipNotificationSwitch() { let isEnabled = isEnabledRemoteNotificationTypes() if (isEnabled
func didFlipNotificationSwitch() {
let isEnabled = isEnabledRemoteNotificationTypes()
if (isEnabled) {
if #available(iOS 8.0, *) {
let settings = UIUserNotificationSettings(forTypes: [.None], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
} else {
UIApplication.sharedApplication().registerForRemoteNotificationTypes([.None])
}
} else {
if #available(iOS 8.0, *) {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
} else {
UIApplication.sharedApplication().registerForRemoteNotificationTypes([.Alert, .Badge, .Sound])
}
}
print("isEnabled \(isEnabled)")
}
isEnabledRemoteNotificationTypes()
是一种方便的方法,可以检查基于操作系统的注册-它可以正常工作。这是:
func isEnabledRemoteNotificationTypes() -> Bool {
if #available(iOS 8.0, *) {
let types = UIApplication.sharedApplication().currentUserNotificationSettings()?.types
if (types == UIUserNotificationType.None) {
return false
} else {
return true
}
} else {
let types = UIApplication.sharedApplication().enabledRemoteNotificationTypes()
if (types == UIRemoteNotificationType.None) {
return false
} else {
return true
}
}
}
问题是,一旦注册(isEnabled
返回true
),我将尝试通过设置类型在本地取消注册到。无,正如您在上面的方法中所看到的。这似乎不起作用。调用将它们设置为.None
的行后,我在设置为后立即在我的appDeldidRegisterUserNotificationSettings
回调中打印通知设置
:
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
}
得到这个:
Printing description of notificationSettings:
<UIUserNotificationSettings: 0x12684c840; types: (UIUserNotificationTypeAlert UIUserNotificationTypeBadge UIUserNotificationTypeSound);>
通知设置的打印说明:
为什么不注册.None
-或者-是否有更好的方法在保持服务器注册的同时关闭通知演示?至少对于远程通知,有一个名为unregisterForRemoteNotifications
的函数。对于用户通知,我尝试了使用[.None]和空数组,但设置仍然没有更改,正如您所指出的-我不知道这是否可行。@peacer212我加入了unregisterForRemoteNotifications
,并注销了从UIApplication.sharedApplication()返回的类型.currentUserNotificationSettings()?.types随后立即
,并检查了appDelegate
回调-两者都显示用户仍在注册。一旦设置了UIUserNotificationType,我就无法成功删除任何UIUserNotificationType。用例是什么?@peacer212我正在应用程序的设置中实现一个切换,以打开/关闭通知,据我所知,一旦授予初始通知类型权限,您就不能以编程方式更改它-只有用户可以。您的应用程序可以选择不使用允许使用的通知类型,但您不能实际减少您拥有的权限。