Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

ios - Programmatically tapping NavigationLink in SwiftUI on push notification

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...