I'm working on App that have push notification property. And I should enable/disable the push notification permission within my app without go to iPhone settings.
Is there a way to implement that?
I searched a lot, but I didn't find any proper way to implement it.
Any help?
If a user denied permissions for push notifications you can not let him enable it from within the app.
You could however, set a button in your settings app (ViewController
), and let the user switch the notifications off and on there. Then you can set a boolean to check before sending notifications. This way a user might use it instead of disabling the app's notification permission on the device settings.
if #available(iOS 10.0, *) {
// SETUP FOR NOTIFICATION FOR iOS >= 10.0
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
}else{
// SETUP FOR NOTIFICATION FOR iOS < 10.0
let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
// This is an asynchronous method to retrieve a Device Token
// Callbacks are in AppDelegate.swift
// Success = didRegisterForRemoteNotificationsWithDeviceToken
// Fail = didFailToRegisterForRemoteNotificationsWithError
UIApplication.shared.registerForRemoteNotifications()
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// ...register device token with our Time Entry API server via REST
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
//print("DidFaildRegistration : Device token for push notifications: FAIL -- ")
//print(error.localizedDescription)
}
UIApplication.shared.unregisterForRemoteNotifications()
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