Search code examples
iosswiftuilocalnotification

Get local notification when App is in foreground Swift 4 iOS 11


I want to receive a Local notification when my app is in foreground, when I tried with below code it never fires a notification, but when I entered app in background it did fired.

here is what I tried:

//Schedule a Local Notification
func ScheduleNotification(timeInterval: Double, repeats: Bool, notificationBody:String, title:String){

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: repeats)

    let center = UNUserNotificationCenter.current()

    let identifier = "UYLLocalNotification"
    let content = UNMutableNotificationContent()
    content.title = title
    content.body = notificationBody
    content.sound = UNNotificationSound.default()
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    center.add(request, withCompletionHandler: { (error) in
        if let error = error {
            //Something went wrong
            print(error.localizedDescription)
        }
    })
}

override func viewDidLoad() {
    super.viewDidLoad()

    if Currentcount < data.count {
        self.ScheduleNotification(timeInterval: 5.0, repeats: false, notificationBody: "You have \(data.count - Currentcount) notification", title: "Alert!")
    }
}

Any help would be appreciated Thanks.


Solution

  • The notification probably also fires while you app is in foreground.

    Per Default, iOS does not show any UI when a notification arrives and the target app is in the foreground. It is the applications job to display the notification contents. Using UNUserNotificationCenterDelegate you can very easily display the notification as an alert. See this post for more information.