iosswiftpush-notificationapple-push-notifications

Show notification in iOS app While app in foreground / Active in swift 3


I am trying to show the Banner notification when the app is active. I used given method but there is no result , Banner notification are appearing only when the app is closed :

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    print("Push notification received: \(userInfo)")

    if application.applicationState == .active {
       print("active")
       let localNotification = UILocalNotification()
       localNotification.userInfo = userInfo
       localNotification.alertAction = "Test"
       localNotification.soundName = UILocalNotificationDefaultSoundName
       localNotification.alertBody = "Notification test!!"
       localNotification.fireDate = Date()
       UIApplication.shared.scheduleLocalNotification(localNotification)
     }
}

It prints "active" but the notification is not showing. Am i missing any step ?

Thank you.


Solution

  • If the application is running in the foreground, iOS won't show a notification banner/alert. You have to write some code to deal with the situation of your app receiving a notification while it is in the foreground.

    Or you can use popular Third party library : github.com/bryx-inc/BRYXBanner

    Use it like below

    import BRYXBanner // import in your class 
    
    // Put this code where you are getting notification 
    let banner = Banner(title: "title", subtitle: "subtitle", image: UIImage(named: "addContact"), backgroundColor: UIColor(red:137.0/255.0, green:172.0/255.0, blue:2.0/255.0, alpha:1.000))
    banner.dismissesOnTap = true
    banner.show(duration: 1.0)
    

    But if You are using iOS 10.0+ then you can approach goal for displaying banner message while app is in foreground, use the following method.

     // This method will be called when app received push notifications in foreground for iOS 10+
     @available(iOS 10.0, *)
     func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
     }