Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask user permission for receiving notifications?

I am using Swift 3.0 and I want the user to be able to click on a button to trigger the alert box that requests his permission for using notifications.

I am surprised not to find more information about that.

I would like to support iOS 9.0 as well as 10.

What is the way to trigger this ask-for-permission alert box again ?

like image 702
lapin Avatar asked May 24 '17 11:05

lapin


People also ask

When should you ask for notification permissions?

All newly-installed apps will need to request user permission before they can send notifications. While existing apps will get their previous permissions temporarily pre-granted when the user upgrades their device to Android 13 or higher.

Do you need consent for push notifications?

Web push notifications require explicit consent from the website visitors by design. All browsers that support web push notifications provide an opt-in for users to subscribe to notifications. For communication meant for all users, this consent would suffice.

How do I allow an app to send me notifications?

Tap an app. Some devices may require you to tap the app name twice. Tap 'Notifications' or 'App notifications'. Tap 'On' or 'Off'.


1 Answers

import UserNotifications

and Declare this UNUserNotificationCenterDelegate Method in header

in appDelegates just put this code :

func registerForRemoteNotification() {
        if #available(iOS 10.0, *) {
            let center  = UNUserNotificationCenter.current()

            center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
                if error == nil{
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }

        }
        else {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

And when user give permission at that time you can get user token via didRegisterForRemoteNotificationsWithDeviceToken Delegates method

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print(token)

        print(deviceToken.description)
        if let uuid = UIDevice.current.identifierForVendor?.uuidString {
            print(uuid)
        }
        UserDefaults.standard.setValue(token, forKey: "ApplicationIdentifier")
        UserDefaults.standard.synchronize()


    }
like image 54
Himanshu Moradiya Avatar answered Nov 15 '22 12:11

Himanshu Moradiya