Jay
Jay

Reputation: 83

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.

Upvotes: 5

Views: 7986

Answers (3)

Kai Zheng
Kai Zheng

Reputation: 8178

You can simply add the willPresent delegate function of UNUserNotificationCenterDelegate to your AppDelegate.

Simply by giving .sound, .banner UNNotificationPresentationOptions into the completion handler, your local notifications will show when your app is in the foreground.

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.sound, .banner])
    }
}

One more step: You of course need to set the UNUserNotificationCenter delegate inside didFinishLaunchingWithOptions.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {  
    UNUserNotificationCenter.current().delegate = self
}

Note

For SwiftUI Cycles, you can access the AppDelegate like so: Here

Upvotes: 0

Niraj Paul
Niraj Paul

Reputation: 1538

Here I am showing you how the UNUserNotificationCenterDelegate is work step by step

  1. In the AppDelegate: import UserNotifications

  2. class AppDelegate: UIResponder,UNUserNotificationCenterDelegate{}

  3. Assign the delegate method to self inside the didFinishLaunchingWithOptions

    func application(_application:UIApplication,
    didFinishLaunchingWithOptionslaunchoptions:[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
           UIApplication.shared.applicationIconBadgeNumber = 0
                let center = UNUserNotificationCenter.current()
                center.delegate = self        
                center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
    
                    if granted {
                        DispatchQueue.main.async { // Correct
                            UIApplication.shared.registerForRemoteNotifications()
                        }
    
                    }
    
                }
    
        }
    
  4. What you want to show in the Local Notification

         func assignValueToNotification
            {
                let content = UNMutableNotificationContent()
                content.body = "Asssign body"
                content.userInfo = ["identifier": "info"]
                content.sound = UNNotificationSound.default()
                content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber;
                content.categoryIdentifier = "write category identifier"
                // Deliver the notification in five seconds.
                let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 0.5, repeats: false)
                let request = UNNotificationRequest.init(identifier: region.identifier as String, content: content, trigger: trigger)
               // Schedule the notification.
               let center = UNUserNotificationCenter.current()
               center.add(request)
        }
    
  5. write down you delegate method, that will be called when you click Local notification.

    func userNotificationCenter(_ center:UNUserNotificationCenter, didReceive response:UNNotificationResponse,withCompletionHandler completionHandler: @escaping () -> Void{
        print("Received Local Notification:")
    }
    

Upvotes: 2

naglerrr
naglerrr

Reputation: 2854

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.

Upvotes: 4

Related Questions