在应用程序设置中实现切换到切换通知

时间:2015-09-22 17:37:31

标签: ios swift notifications

我正在尝试在我的应用程序的本地SettingsVC中实现一个Switch来切换Notification On / Off。我现在决定让用户注册服务器(APNS和AppBoy),只需切换开/关通知的本地演示。

(如果用户之前已经注册过。如果他们还没有注册过,那么这段代码应该在他们第一次翻到“on”时注册)

当用户翻转开关时,这是我的代码:

    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。这似乎不起作用。在将广告设置为.None后,我会在设置为notificationSettings后立即在我的appDel didRegisterUserNotificationSettings回调中打印.None

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {

}

得到这个:

Printing description of notificationSettings:
<UIUserNotificationSettings: 0x12684c840; types: (UIUserNotificationTypeAlert UIUserNotificationTypeBadge UIUserNotificationTypeSound);>

为什么不注册.None - 或者 - 是否有更好的方法可以在保持服务器注册的同时关闭通知演示文稿?

0 个答案:

没有答案