10

I am using SwiftUI.

I want to open a specific screen other than Root View by clicking the push notification. There are several ways to open it using StoryBoard, but not without StoryBoard.

How can I achieve it without using StoryBoard?

I tried this, but I'm a beginner, so I don't know.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    var window: UIWindow?

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

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
        // I want to open a screen other than Root View here.
        completionHandler()
    }
    ... }
Jonas Deichelmann
  • 3,513
  • 1
  • 30
  • 45
Ika
  • 1,271
  • 1
  • 12
  • 20
  • Have you found an answer yet? – Adit Gupta Sep 09 '20 at 18:03
  • The question does not have much sense because `userNotificationCenter(_ center: UNUserNotificationCenter, didReceive...` is called while application is in background, so no UI is present then, and you just need to store somewhere notification response data to show user later, when user opens an app, but then app just behaves as in regular flow (eg. read records from database, defaults, etc.) – Asperi Sep 10 '20 at 17:12
  • Here is a similar question to yours, maybe the answer will help: https://stackoverflow.com/questions/60490860/display-a-view-after-receiving-apns-with-swiftui – Jonas Deichelmann Sep 12 '20 at 11:14

1 Answers1

1

The idea is you set a variable when the user is coming from a notification and check that variable when you want to present the UI.

here is a sample:

// assume that AppDelegate is also our UNNotificationCenterDelegate 
// I'm using a bool variable to check if user is coming from the notification
var isFromNotif: Bool = false
extension AppDelegate: UNUserNotificationCenterDelegate {
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        isFromNotif = true
        // ...
    
}

now in my View, I check the flag.

struct ContentView1: View {
    
    var body: some View {
        return Group {
            if isFromNotif {
                Text("coming from notification")
            } else {
                Text("not coming from notification")
            }
        }
    }
    
}

I hope this sample could help you.

Mohammad Rahchamani
  • 5,002
  • 1
  • 26
  • 36