Local notification is not coming in forgeound in iOS 10.2

846 views Asked by At

I have implemented local notification successfully for iOS 10.2.

But problem is that notification alert only comes if the app is in the background no alert come if the app is foreground.

Is it possible to get local notification in the foreground?

My code is here

func notificationNow(){

        print("notification will be triggered in five seconds..Hold on tight")
        let content = UNMutableNotificationContent()
        content.title = "Intro to Notifications"
        content.subtitle = "Lets code,Talk is cheap"
        content.body = "Sample code from WWDC"
        content.sound = UNNotificationSound.default()

        //To Present image in notification
        if let path = Bundle.main.path(forResource: "menu2", ofType: "png") {
            let url = URL(fileURLWithPath: path)

            do {
                let attachment = try UNNotificationAttachment(identifier: "sampleImage", url: url, options: nil)
                content.attachments = [attachment]
            } catch {
                print("attachment not found.")
            }
        }

        // Deliver the notification in five seconds.
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5.0, repeats: false)
        let request = UNNotificationRequest(identifier:requestIdentifier, content: content, trigger: trigger)

        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().add(request){(error) in

            if (error != nil){
                print(error?.localizedDescription as Any)
            }
        }
    }
4

There are 4 answers

2
miOS On BEST ANSWER

Write following code (extension) in the class where you want to observe the local notification

This will notify when you receive notification in foreground or user tapped on notification when the app is in background.

Hope this will solve your problem.

extension ViewController:UNUserNotificationCenterDelegate{


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

    print("Tapped in notification")
}

//This is key callback to present notification while the app is in foreground
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    print("Notification being triggered")
    //You can either present alert ,sound or increase badge while the app is in foreground too with ios 10
    //to distinguish between notifications
//        if notification.request.identifier == requestIdentifier
//        {

        completionHandler( [.alert,.sound,.badge])

//        }
       }

}
1
Arasuvel On

When the app is running in Foreground. You need to capture the Local Notification through delegate methods.

So in your AppDelegate implement the listening for delegate in didFinishLaunchingWithOptions method:

It is important to set the delegate before your app finishes launching.

// Do NOT forget to retain your delegate somewhere
let notificationDelegate = UYLNotificationDelegate()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  let center = UNUserNotificationCenter.current()
  center.delegate = notificationDelegate

  // ...
  return true
}

If you want to respond to actionable notifications or receive notifications while your app is in the foreground you need to implement the UNUserNotificationCenterDelegate. This protocol defines two optional methods:

  • userNotificationCenter(_:willPresent:withCompletionHandler:) is
    called when a notification is delivered to a foreground app. You
    receive the UNNotification object which contains the original
    UNNotificationRequest. You call the completion handler with the
    UNNotificationPresentationOptions you want to present (use .none to
    ignore the alert).

  • userNotificationCenter(_:didReceive:withCompletionHandler:) is called when a user selects an action in a delivered notification. You receive the UNNotificationResponse object which includes the actionIdentifier for the user action and the UNNotification object. The system defined identifiers UNNotificationDefaultActionIdentifier and UNNotificationDismissActionIdentifier are used when the user taps the notification to open the app or swipes to dismiss the notification.

In both cases you must call the completion handler once you finish.

#pragma mark - UNUserNotificationCenterDelegate Methods

func userNotificationCenter(_ center: UNUserNotificationCenter,
   willPresent notification: UNNotification, 
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// Play sound and show alert to the user
     completionHandler([.alert,.sound])
}
0
Ketan Parmar On

Use below method to configure notification to show in foreground,

 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

You can refer Apple documentation for more details!

0
rosem On

In the documentation for UNUserNotificationCenterDelegate:

Important

You must assign your delegate object to the UNUserNotificationCenter object no later before your app finishes launching. For example, in an iOS app, you must assign it in the application(:willFinishLaunchingWithOptions:) or application(:didFinishLaunchingWithOptions:) method.

You appear to be setting the delegate much later — just before the notification is added to the notification center.

I created a simple Swift class singleton with an extension to conform to UNUserNotificationCenterDelegate. In the singleton's init method I assigned the delegate to self. I then initialize the singleton in the AppDelegate's willFinishLaunchingWithOptions method.