1

Is there a way to get Push notification token when user enabled it manually from settings while the application was in the background. Is there a function available in Swift which will get push notification token when user will come back to the app.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
MarJano
  • 1,257
  • 2
  • 18
  • 39
  • You can register for push notifications and receive a token without asking the user. The authorization request is to display the notifications, not to receive them. – jcaron Nov 22 '17 at 17:57
  • Don't understand so I can have token without asking for user permissions. Any sample code how this would work – MarJano Nov 22 '17 at 18:27

2 Answers2

1

When user turing push notification allowed in the general setting of ios, the app can call the

UIApplication.shared.registerForRemoteNotifications()

and device token is able to be obtained from

public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)

as I understand there is no any direct method to determine the user setting push notification manually, so I came up two alternative ways

  1. using NSNotification center observer to determine any setting changes as explained already here
  2. or in the Appdelegate applicationWillEnterForeground

to call bellow function (for example)

    func registerRemoteNotification() {
     let notificationCenter = UNUserNotificationCenter.current()
     notificationCenter.getNotificationSettings { (settings) in
        if settings.authorizationStatus == .authorized {
            //"authorized"
            DispatchQueue.main.async {
              UIApplication.shared.registerForRemoteNotifications()
             }
        } else {
          //"not authorized")
        }
      } 
    }
Kakoo
  • 11
  • 1
  • 3
0

You can use observer for system wise settings change. See more info on this thread

ahmed
  • 540
  • 2
  • 18
  • So how this will be called and token set? public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { UserDefaults.standard.set(deviceToken, forKey: "deviceToken") } – MarJano Nov 23 '17 at 12:05