Enable or Disable Iphone Push Notifications inside the app

后端 未结 4 1399
终归单人心
终归单人心 2020-12-01 04:52

I have a iphone app which is enable to receive push notifications. Currently i can disable push notifications for my app by going to the iphone settings/Notifications.

4条回答
  •  暖寄归人
    2020-12-01 05:11

    Pragmatically, it is possible to enable & disable push notification by registering and unregistering push notification.

    Enable Push Notification:

    if #available(iOS 10.0, *) {
       // 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{
        // Below iOS 10.0
    
        let settings = UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)
    
        //or
        //UIApplication.shared.registerForRemoteNotifications()
    }
    

    Delegate methods

    @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) {
        // .. Receipt of device token
    }
    
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // handle error
    }
    

    Disable Push Notification:

    UIApplication.shared.unregisterForRemoteNotifications()
    

提交回复
热议问题