I have a very simple app displaying a list and each row is a NavigationLink to the detail view. This is a simplified version with what I think are the most important parts:
class Element: ObservableObject {
@Published var id: String
...
}
class ListViewModel: ObservableObject {
@Published var elements: [Element]
...
}
struct ContentView: View {
@ObservedObject private var viewModel: ListViewModel
@EnvironmentObject private var pushHandler: PushNotificationHandler
var body: some View {
List(viewModel.elements) {
NavigationLink(destination: DetailView(element: element)) {
...
}
}
}
}
Now the app receives push notifications referring to each of the elements by id, i.e. the userInfo dictionary contains one of the ids belonging to an Element
. What I would like to do now is navigate directly to the DetailView
when the user taps on the push notification.
I also have a class listening to notification center delegate calls that looks something like this:
class PushNotificationHandler: NSObject, UNUserNotificationCenterDelegate, ObservableObject {
@Published var lastNotificationResponseID: String?
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
lastNotificationResponseID = response.notification.request.content.userInfo["id"] as? String
}
}
So far I have discovered that NavigationLink
can be created with isActive
, which is a Binding<Bool>
and which when set to .constant(true)
pushes the DetailView
as soon as I start the app.
My problem is - how do I pipe the lastNotificationResponseID
into the NavigationLink
's isActive
and compare it to element.id
of the corresponding row so that the correct DetailView
is pushed when the push is tapped?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…