swiftswiftuiwidgetunusernotificationcenter

How to handle UserNotification through widget iOS14 to main app in swift?


I have an iOS app with widget iOS 14 where I send UserNotifications from both sides. On main app side all UNUserNotificationCenterDelegate is working fine. On widget side when I fetched events from calendar then UserNotifications are triggered. When I'm received notification in main-app side and click on it, then didReceive response: UNNotificationResponse delegate or other delegates did not called and also did not called in widget side.

here is my code in Widgets

class NotificationCenter: NSObject, ObservableObject {
    @Published var dumbData: UNNotificationResponse?
    
    override init() {
        super.init()
        UNUserNotificationCenter.current().delegate = self
    }
}
extension NotificationCenter: UNUserNotificationCenterDelegate  {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }

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

    func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
        
    }
    func scheduleNotification(at date: Date, identifierUnic : String, body: String, titles:String) {
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

        let triggerWeekly = Calendar.current.dateComponents([.day, .month, .hour,.minute, .year], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
        let content = UNMutableNotificationContent()
        content.title = titles
        content.body = body
        content.sound = UNNotificationSound.default
        content.categoryIdentifier = "todoList2"
        
        let request = UNNotificationRequest(identifier: identifierUnic, content: content, trigger: trigger)
        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print(" We had an error: \(error)")
            }}
    }
}
//and fire in 
@ObservedObject var notificationCenter: NotificationCenter

 func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        eventManager.checkPermission { (eventArray) in
            print(eventArray)
            if eventArray.count > 0{
                for item in eventArray{
                    notificationCenter.scheduleNotification(at: item.startDate ?? Date(), identifierUnic: item.eventIdentifier ?? "", body: item.title, titles: item.title)
                }
            }
        }
        
        var entries: [SimpleEntry] = []
        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let entryDate = Calendar.current.date(byAdding: .second, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate)
            entries.append(entry)
        }
        
        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }

On Main App Side

     func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
         let userInfo = response.notification.request.content.userInfo
        print("userInfo \(userInfo)")
}

Please let me know? Thank you


Solution

  • I have a similar situation that I still can't figure out how to do... I have a widget that will display calendar events. How can I refresh the widget when calendar changed? I tried to use notificationCenter but don't know where to put it. What I want to do is that when there is a calendar change, my widget should be reloaded (refresh timeline.)

    Thank you for your help.