如何正确禁用/启用推送通知

时间:2019-08-12 08:00:54

标签: ios swift firebase push-notification

您好,其他开发人员。

我正在尝试使用UISwitch创建一个操作,该操作允许用户禁用/启用其推送通知。当我关闭开关时,我不再收到推送通知。但是,如果我尝试将其重新打开,仍然不会收到。也使用Firebase。

这里有我的App委托代码。我将尝试共享相关代码,但如有需要,请随时请求更多代码。

PS:我用于切换器的代码实际上来自我在StackOverFlow上找到的答案。

// App delegate

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("Registered for notifications", deviceToken)
        Messaging.messaging().apnsToken = deviceToken

    }

    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
        print("Registered with FCM with token:", fcmToken)
    }

  private func attemptRegisterForNotifications(application: UIApplication) {
        // APNS means Apple push notification services
        print("Attempting to register APNS...")

        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self



        // user notification auth
        // all of this works for iOs 10+
        let options: UNAuthorizationOptions = [.alert, . badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: options) { (granted, error) in
            if let error = error {
                print("Failed to request auth:", error)
                return
            }

            if granted {
                print("Auth granted.")
            } else {
                print("Auth denied")
            }

        }

        application.registerForRemoteNotifications()


    }

这是设置视图控制器中的代码


   self.notificationSwitch.addTarget(self, action: #selector(action(sender:)), for: .valueChanged)...

 @objc func action(sender: UISwitch) {

        let userDefaults = UserDefaults.standard
        userDefaults.set(sender.isOn, forKey:"identifier")

        if(notificationSwitch.isOn) {
            print("Switch is on")
            UIApplication.shared.registerForRemoteNotifications()

        } else {

            print("Switch is off")
            UIApplication.shared.unregisterForRemoteNotifications()
        }

    }

1 个答案:

答案 0 :(得分:0)

根据unregisterForRemoteNotifications的文档:

  

仅在少数情况下(例如当   该应用程序的新版本取消了对所有类型的遥控器的支持   通知。用户可以暂时阻止应用接收   通过“设置”的“通知”部分进行远程通知   应用程式。通过此方法取消注册的应用程序始终可以重新注册。

正确的方法(实际上是我在工作的项目中所看到的方法)是调用api并告诉后端不应发送推送通知。