1

I'd like to create Attendance management app for iOS. The app will have start button, then if it tapped the app would have banner notification to greet you.

The problem is I can't have banner notification while the app is foreground. I'll show my code below. If I want to get a notification, I have to return home screen or run other apps instead. On my app, Set Notification button is enable to have notifications, and Start button is for set notification. I would have notification immediately, but at this moment I have to go back to home, so I set the timing timeInterval: 5.

ContentView.swift

import SwiftUI
import Foundation
import UserNotifications

struct ContentView: View {
    var body: some View {
        VStack {
            Button(action: { self.setNotification() }) {
                Text("Set Notification")
            }.padding()

            //added here
            Button(action: { self.btnSend() }) {
                Text("Start")
            }.padding()
        }
    }

    func setNotification() -> Void {
     UNUserNotificationCenter.current().requestAuthorization(
                       options: [.alert,.sound,.badge], completionHandler: {didAllow,Error in
                       print(didAllow) //
                    })
    }

    func btnSend() {
        print("btnSend")

        let content = UNMutableNotificationContent()
        content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
        content.body = NSString.localizedUserNotificationString(forKey: "Good morning hehe", arguments: nil)
        content.sound = UNNotificationSound.default

        // Deliver the notification in five seconds.
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "FiveSecond",
                                            content: content, trigger: trigger) // Schedule the notification.
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error : Error?) in
             if let theError = error {
                 // Handle any errors
             }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Do anyone have nice solutions?

Haru
  • 65
  • 1
  • 7
  • 2
    Does this answer your question? [Get push notification while App in foreground iOS](https://stackoverflow.com/questions/14872088/get-push-notification-while-app-in-foreground-ios) – El Tomato Jan 10 '20 at 01:11

3 Answers3

4

May be you just need to add some codes in the AppDelegate.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    // add UNUserNotificationCenterDelegate
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions)
        -> Void) {
        completionHandler([.alert, .badge, .sound])
    } // add this function

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        UNUserNotificationCenter.current().delegate = self // add this
        return true
    }

    // ... omitted
}
Lin
  • 41
  • 2
  • Perfect solution. – Vinayak Bhor Nov 28 '20 at 06:27
  • 1
    I have this with my SwiftUI based app, which has an AppDelegate and SceneDelegate. When my app is in the foreground, I get the push notification sound, and it's delivered to the iOS Notification Center, but I don't see it. I have to manually go to the iOS Notification Center to see it. – Chris Prince Feb 13 '21 at 19:27
3

Use the

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

method for foreground notification capturing and show alert, badge and add sound.

1

The notification banner does not show if the app is in foreground, you need to capture the notificafion in the AppDelegate, create your own custom view and handle it from there.

javier rivarola
  • 500
  • 3
  • 6