-1

I am working on swift 4.2.I am getting notifications when app is background but i am not getting when app is active.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.alert, .badge, .sound])
}

I would like to know how to get a notification when the app is open

Swifty
  • 839
  • 2
  • 15
  • 40
mouli
  • 21
  • 5
  • Why do you think you don't get it? it just not displayed. see https://stackoverflow.com/questions/30852870/displaying-a-stock-ios-notification-banner-when-your-app-is-open-and-in-the-fore – Kirow Jun 11 '19 at 11:06

2 Answers2

1

You need to confirm UNUserNotificationCenterDelegate in your AppDelegate class;

import UserNotifications

class AppDelegate : UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

      UNUserNotificationCenter.current().delegate = self

   }

then you can call this function in your ViewController class, don forget to import UserNotifications again in ViewController;

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) 
{
    completionHandler([.alert, .badge, .sound])
}
0

update this code with above mentioned code

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler:
        @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Handle push from foreground")
        print("\(notification.request.content.userInfo)")
        completionHandler([.alert, .badge, .sound])

        return
    }
Jins George
  • 121
  • 6