Search code examples
iosxcodeswift3uilocalnotificationlocalnotification

Local notification is not coming in forgeound in iOS 10.2


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)
            }
        }
    }

Solution

  • 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])
    
    //        }
           }
    
    }