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?
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
UserNotifications
framework where you use this code.didRegisterForRemoteNotificationsWithDeviceToken
method in your AppDelegate
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
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With