Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 581
Jay Avatar asked Jan 04 '18 09:01

Jay


2 Answers

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.

like image 195
naglerrr Avatar answered Sep 26 '22 23:09

naglerrr


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:")
    }
    
like image 37
Niraj Paul Avatar answered Sep 23 '22 23:09

Niraj Paul