如何从 onContinueUserActivity 更改 WindowGroup 视图?

How to change WindowGroup view from onContinueUserActivity?

我有一个深度链接的应用程序,所以首先我有一个加载或主页视图呈现:

@main
struct AppMain: App {
    
    var body: some Scene {
        WindowGroup {
            LoadingView()
                .onContinueUserActivity(NSUserActivityTypeBrowsingWeb, perform: handleUserActivity)
        }
    }
}

但是,在响应 activity 的 handleUserActivity 中,如何根据 activity 参数更新屏幕?例如,我提取了一个值并想从这里呈现视图:

private extension AppMain {
    
    func handleUserActivity(_ userActivity: NSUserActivity) {
        guard let url = userActivity.webpageURL,
              let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
              let queryItems = components.queryItems
        else {
            return
        }
        
        if let modelID = queryItems.first(where: { [=11=].name == "id" })?.value {
            SmoothieView(id: modelID) // TODO: How to I render view??
        }
    }
}

如何替换 LoadingView 并显示 SmoothieView

这里有一个可能的方法——在顶部视图中使用应用程序状态对象和观察者来根据状态进行切换。

(注意:代码输入到位,因此可能有错别字)

class AppState: ObservableObject {
   @Published var modelID: String?
}

@main
struct AppMain: App {
    @StateObject var appState = AppState()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appState)
                .onContinueUserActivity(NSUserActivityTypeBrowsingWeb, perform: handleUserActivity)
        }
    }
}

private extension AppMain {
    
    func handleUserActivity(_ userActivity: NSUserActivity) {
        guard let url = userActivity.webpageURL,
              let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
              let queryItems = components.queryItems
        else {
            return
        }
        
        if let modelID = queryItems.first(where: { [=10=].name == "id" })?.value {

            self.appState.modelID = modelID // << here !!

        }
    }
}

// as soon as you receive model id the view will be refreshed
struct ContentView: View {
   @EnvironmentObject var appState: AppState

   var body: some View {
      if appState.modelID == nil {
         LoadingView()
      } else {
         SmoothieView(id: appState.modelID!)
      }
   }
}