7

For ios 10 i used this for registering the push notifications :

Registering for Push Notifications in Xcode 8/Swift 3.0?

Is there a way to ask for the requestAuthorization(options:[.badge, .alert, .sound]) outside the appdelegate and the func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool

The reason i ask is because i don't want to present the pop up for push notifications after the user has used the app for a bit. Any ideas?

Community
  • 1
  • 1
Pavlos
  • 203
  • 4
  • 9

2 Answers2

8

Like @dan said it isn't necessary to request the notifications permission in the AppDelegate. You can do it wherever you want to. This is what you probably be doing for that.

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
    if error == nil {
        if success {
            print("Permission granted")
            // In case you want to register for the remote notifications
            let application = UIApplication.shared
            application.registerForRemoteNotifications()
        } else {
            print("Permission denied")
        }
    } else {
        print(error)
    }
}

And Remember

  1. to import the UserNotifications framework where you use this code.
  2. if you register for remote notifications you need to implement the didRegisterForRemoteNotificationsWithDeviceToken method in your AppDelegate
maxwell
  • 3,788
  • 6
  • 26
  • 40
Adeel Miraj
  • 2,472
  • 3
  • 22
  • 32
  • 1
    But before asking for user Authorization, can I call `UIApplication.shared.registerForRemoteNotifications()` to get the token first? Or I have to wait after the user authorized? – NeoWang Oct 15 '17 at 17:53
  • @NeoWang this method actually initiates the permissions request if the user hasn’t granted already. And remember without the permission you do not get the device token. – Adeel Miraj Oct 16 '17 at 03:17
  • 1
    I think device token is thrown to app before the user grant the permission – SuryaKantSharma Oct 14 '19 at 09:24
  • @NeoWang Yes you can call. check the sample app from apple https://developer.apple.com/documentation/usernotifications/implementing_alert_push_notifications – YodagamaHeshan Nov 03 '22 at 07:00
4

The question for me is the pop up won't show again once user agreed or denied it. So we have to redirect users to Settings after that manually.

Here comes the code in Swift:

@IBAction func userDidClickButton(_ sender: Any) {

    // initialise a pop up for using later
    let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)
    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
            // do something
            }
         }
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)

    // check the permission status
    UNUserNotificationCenter.current().getNotificationSettings () { settings in            
        switch settings.authorizationStatus {
        case .denied, .notDetermined:
            self.present(alertController, animated: true, completion: nil)
        case .authorized:
            // continue the stuff
            DispatchQueue.main.sync {
                // Update UI
            }
        }
    }
}
Allen
  • 2,979
  • 1
  • 29
  • 34