为什么我不能注册我的设备后注销苹果推送消息?

这是我之前问的问题的后续问题如何注册用户的iOS设备从AppDelegate以外的地方接收推送消息?

目前在我的Swift应用程序中,我有一个默认设置为closures的UISwitch ,当用户打开它时 – 我希望他注册接收推送通知。 但是,当他closures这个function时,他应该从推送通知中取消注册(并且以后不会收到任何推送消息,直到再次注册)。

所以我创build了一个pipe理推送注册的类:

 class NotificationManager { static var shared = NotificationManager() private var application : UIApplication? func setup(application: UIApplication) { self.application = application } func register () { guard let application = application else { print("Attempt to register without calling setup") return } print("registering for push") let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound] let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil) application.registerUserNotificationSettings(pushNotificationSettings) application.registerForRemoteNotifications() } func unregister(){ guard let application = application else { print("Attempt to register without calling setup") return } print("unregistering for push") let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound] let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil) application.registerUserNotificationSettings(pushNotificationSettings) if(application.isRegisteredForRemoteNotifications){ print("unregistering went ok") application.unregisterForRemoteNotifications() } } } 

然后我的UISwitch听众是:

 func messagesStateChanged(_ sender: UISwitch){ if(sender.isOn){ defaults.set("true", forKey: "popupMessages") defaults.synchronize() NotificationManager.shared.register() } else { defaults.set("false", forKey: "popupMessages") defaults.synchronize() NotificationManager.shared.unregister() } } 

现在在我的AppDelegate我有以下方法:

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) print(deviceTokenString) } 

并且当用户第一次打开开关时 – 我看到stringregistering for push控制台中打印的registering for push和设备令牌。

当用户closures开关时,我在控制台中看到:

 unregistering for push unregistering went ok 

但是,当我再次打开开关时,我只能看到:

 registering for push 

我没有看到一个令牌string。 看起来像从AppDelegate的方法: didRegisterForRemoteNotificationsWithDeviceToken永远不会被调用。 当我稍后关掉开关时,我也只看到:

 unregistering for push 

我没有得到一个确认, unregistering went ok

为什么我不能取消注册,然后再次注册推送消息?

我已经devise了这一切,因为我想添加用户select接收推送通知或不直接在我的应用程序。