Hello fellow developers.
I am trying to create an action using a UISwitch that allows users to disable/enable their push notifications. When I turn the switch off I don't receive the push notifications anymore. However if I try turning it back on I still do not receive it. Using Firebase as well.
Heres my App delegate code. I'll try to share relevant code but please feel free to request more pieces of code if you need.
PS: The code I am using for the switcher is actually from an answer I found on 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()
}
Here is the code I have in the settings view controller
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()
}
}