这是我之前在How can I register user's ios device for receiving push messages from place other than AppDelegate?
提出的问题的后续跟进目前在我的Swift
应用程序中,我有一个UISwitch
默认设置为关闭,当用户打开它时 - 我希望他注册接收推送通知。但是,当他关闭该开关时 - 他应该从推送通知中取消注册(以后不再接收任何推送消息,直到再次注册)。
所以我创建了一个用于管理推送注册的类:
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)
}
当用户第一次打开开关时 - 我看到控制台中打印了字符串registering for push
和设备令牌。
当用户关闭开关时,我在控制台中看到:
unregistering for push
unregistering went ok
但是,当我再次打开开关时,我只看到:
registering for push
我没有看到令牌字符串。似乎来自AppDelegate
的方法:永远不会调用didRegisterForRemoteNotificationsWithDeviceToken
。当我稍后关闭开关时,我也只看到:
unregistering for push
我没有得到unregistering went ok
的确认。
为什么我无法取消注册然后再次注册推送消息?
我设计的都是这样的,因为我想为用户添加接收推送通知的选择,而不是直接在我的应用程序中。