0

Im trying to run a code (here I print in console) when the notification appears on screen even if user is not interacting with it, but nothing happens, what am I missing?

import SwiftUI
import UserNotifications


class MyUserNotificationCenterDelegate : NSObject, UNUserNotificationCenterDelegate
{
    func userNotificationCenter( center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
    {
        
    }
    
    func userNotificationCenter( center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
    {
        print("notification arrived")
        completionHandler()
    }        
}

struct ContentView: View
{    
    var body: some View
    {
        VStack
        {
            Button("Permission")
            {
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                    if success {
                        print("Done!")
                    } else if let error = error {
                        print(error.localizedDescription)
                    }
                }
            }

            Button("Schedule")
            {
                let content = UNMutableNotificationContent()
                content.title = "notification"
                content.subtitle = "subtitle"
                content.sound = UNNotificationSound.defaultCritical

                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)

                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                UNUserNotificationCenter.current().add(request)
                              
                
            }
            Button("Stop")
            {                UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
            }
        }        
    }
}

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

I tried conforming the notification delegate UNUserNotificationCenterDelegate as you can see, but maybe I did forget something here, or this is not what is called when notification just shows up

  • 2
    Where do you set the delegate for `UNUserNotificationCenter`? – HangarRash Dec 16 '22 at 22:24
  • Thanks for your reply, I thought I was making it in the class I made, isnt that doing it? – codebreaker Dec 16 '22 at 23:53
  • 1
    See https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649522-delegate – HangarRash Dec 17 '22 at 00:00
  • https://stackoverflow.com/questions/70439363/problem-using-a-switch-to-set-a-timeinterval/70442990#70442990 – lorem ipsum Dec 17 '22 at 04:55
  • Thanks everyone and @loremipsum thanks for showing this, but I dont see the function that is called when notification appears, I think that userNotificationCenter should be the one being called when notification appears but its not working for me from that code you provided, should this function be called by system when the notification appears even if user is not interacting with it? – codebreaker Dec 17 '22 at 14:22
  • @loremipsum I just noticed the function is called but only if app is in foreground, how can this be changed so that it reacts when app is in background? – codebreaker Dec 17 '22 at 15:02
  • I didn't mark it as an answer it is just a basic setup, You can add any delegate methods you would like. The basic error in your code is that while you have a class that conforms to the delegate you don't actually tell the Notification Center that you have it. That sample code is just to get you started. Read through the documentation of the delegate and you can find the method that is called for you particular circumstance. – lorem ipsum Dec 17 '22 at 16:27
  • @loremipsum thanks a lot really, well I have this problem, I have found after reading in the docs that didReceiveRemoteNotification should be the function to be used (Im making watchOS app) but the issue is this is never being called, and I have enabled this in signing and capabilities, so this should work but its not doing that, I only get the other function to be executed when application is in foreground but background activity is never calling a function, dont know if it has a special requisite for this – codebreaker Dec 18 '22 at 01:10
  • Remote notifications is for when a notification is sent through APNS you aren’t doing that at least not with this code. – lorem ipsum Dec 18 '22 at 01:19
  • @loremipsum thanks a lot, but then how is it possible to trigger action when notification is shown in screen even if user is not interacting with the notification itself? all the related info I find in the docs seems to be related to remote notification instead but I have seen app do this without having remote notifications – codebreaker Dec 18 '22 at 17:18

0 Answers0