Reputation: 1190
I am using Push Notifications in my SwiftUI app. The thing I need is when I tap on the notification I have to open a specific View. This is working fine when the app is in foreground or in background mode. But when the app is been killed and then I tap on the notification, it only opens the app and it doesn't go to that specified View.
Here is what I tried.
My code in AppDelegate:
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID from userNotificationCenter didReceive: \(messageID)")
}
print(userInfo)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
NotificationCenter.default.post(name: Notification.Name("request_notification"), object: nil, userInfo: userInfo)
}
completionHandler()
}
And in my ContentView:
struct ContentView: View {
@State var msgId = ""
@State var moveToNextView = false
var body: some View {
VStack {
Text("Content View")
}.background(hiddenNav())
.onAppear {
NotificationCenter.default.addObserver(forName: Notification.Name("message_notification"), object: nil, queue: .main) { notification in
print(notification)
let userInfo = notification.userInfo
self.msgId = userInfo["message_id"] as? String // this gives me my message_id = 01
self.moveToNextView.toggle()
}
}
}
func hiddenNav() -> some View {
ZStack {
NavigationLink("", destination: NotificationsView(msgId: self.msgId), isActive: $moveToNextView)
}
}
}
What I need is, when the app is been killed and then I tap on notification, it should take me to my specified View.
Upvotes: 1
Views: 391