in Xcode how can i show local notification of both "foreground and background" mode?

801 views Asked by At

my below code only sends local notifications when foreground. how can i show local notification of both "foreground and background" mode? can anyone provide a code ? thank you o.k

@main
struct ozApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate


    var body: some Scene {
        WindowGroup {
            ContentView().onAppear {   self.send()  }
            
        }
    }

func send(){
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("All set!")
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
         
        
        var content = UNMutableNotificationContent()
        content.title = "Message1"
        content.subtitle = "subtitle"
        content.body = "body"
        content.sound = UNNotificationSound.default
        var request = UNNotificationRequest(identifier: UUID().uuidString , content: content, trigger: nil)
        UNUserNotificationCenter.current().add(request)

and i also have this section


class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // Show local notification in foreground
        UNUserNotificationCenter.current().delegate = self
        
        return true
    }
}
// Conform to UNUserNotificationCenterDelegate to show local notification in foreground
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .badge, .sound])
    }
}

1

There are 1 answers

5
Mahmoud Eissa On

I think you miss the trigger, the below code works fine

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
var content = UNMutableNotificationContent()
 content.title = "Message1"
         content.subtitle = "subtitle"
         content.body = "body"
         content.sound = UNNotificationSound.default
         var request = UNNotificationRequest(identifier: UUID().uuidString , content: content, trigger: trigger)
         UNUserNotificationCenter.current().add(request)

enter image description here