Search code examples
iosswiftswift3unusernotificationcenter

Why is my local notifications not triggered in the foreground in iOS 10?


I'm trying to understand why the local notifications is not being displayed in the foreground. I believe I added all the correct code to allow this ability but no banner is showing when my app is in the foreground.

Here's what I added in AppDelegate.swift:

import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate
{
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
    {
        UNUserNotificationCenter.current().requestAuthorization(options: [UNAuthorizationOptions.alert, UNAuthorizationOptions.sound, UNAuthorizationOptions.badge]) { (willAllow: Bool, error: Error?) in

            if willAllow == true
            {
                // Do something
            }

        }

        UNUserNotificationCenter.current().delegate = self

        // Override point for customization after application launch.
        return true
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        print("GO IN HERE")
        completionHandler(.alert)
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {

    }

}

My ViewController.swift:

override func viewDidLoad()
{
    super.viewDidLoad()

    let content: UNMutableNotificationContent = UNMutableNotificationContent()
    content.sound = UNNotificationSound.default()
    content.subtitle = "This is a test"

    let trigger: UNTimeIntervalNotificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    let request: UNNotificationRequest = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}

When my app launches for the first time, I do see a permissions alert to allow my app to push notifications, but I don't see any notifications at all.

I do see the log output GO IN HERE, so willPresent is being called.

Is there something else that I'm missing?


Solution

  • In reference to the following answer: UserNotification is not showing (iOS 10)

    The reason why my local notifications was not presented in the foreground is not because I "will never see the notifications in the foreground" as mentioned by the previous answer, but because I'm required to set at least the body content, and I did not set that in my code.

    By setting content.body = "Some message", I can finally see the notification in the foreground while my app is running.