Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to tap a push notification to open a specific screen in SwiftUI

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()
    }
    ... }
like image 898
Ika Avatar asked Apr 15 '20 04:04

Ika


People also ask

How do I customize push notifications in Swift?

Go to xcode select File > New > Target > Notification Content Extension > Next > Product Name( name it as CustomUI) > Finish > Active scheme popUp(if comes then select cancel). Every Custom UI must have its unique category Identifier.


1 Answers

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.

like image 113
Mohammad Rahchamani Avatar answered Oct 26 '22 19:10

Mohammad Rahchamani