首页 > 解决方案 > 通知 SwiftUI 父/主机视图结束 Class URLSession 任务的正确方法是什么?

问题描述

场景:中使用异步会话来访问离线服务器。每个来自容器视图的请求上下文都可以通过类枚举
访问 多个端点。数据在其他端点中 累积在Singleton 类中,以便通过成员视图更快地访问。

每个端点显示一个成员视图。

目标:在请求的端点返回数据显示后通知父View ;依次填充特定的成员视图。

问题:不用说,成员视图总是在接收数据之前渲染。
也就是说,它不同步。

事实上,查看数据的唯一方法是通过容器视图上的按钮来按需显示包含数据的成员视图。这不是我想要的。我希望这在选择数据源时自动发生。

我的解决方案:一旦数据可用,就向容器视图发出通知 ,以便容器视图可以使用数据呈现适当的成员视图。

问题:我正在使用发布者订阅方案来等待通知,以便显示数据。
但我对在容器视图中处理订阅者感到困惑。

我正在考虑使用处理程序@Objc 函数与发布/订阅的**NSNotification** 使用。
但我在这里将命令与主观范式混合在一起。

以下代码在收到数据后发布通知:

   case .AppleCountryProvince:
        let url = URL(string: "https://disease.sh/v3/covid-19/apple/countries/Canada")!
        let remoteDataPublisher = URLSession.shared.dataTaskPublisher(for: url)
            .map(\.data)
            .receive(on: DispatchQueue.main)
            .decode(type: DMAppleSubRegion.self, decoder: JSONDecoder())
            .print("AppleSubRegion: ")

        remoteDataPublisher
            .eraseToAnyPublisher()
            .sink(receiveCompletion: { completion in
                switch completion {
                case .finished:
                    print("Publisher Finished")
                case let .failure(anError):
                    Swift.print("\nReceived error: ", anError)
                }
            }, receiveValue: { someValue in
                SingletonData.shared.appleSubRegion = someValue
                NotificationCenter.default.post(name: noteName, object: DataModelType.AppleCountryProvince)
            }).store(in: &cancellables)

以下代码片段在视图的函数中处理通知。
这不是开枪。

    _ = NotificationCenter.default
        .publisher(for: noteName)
        .sink { note in
            if let source = note.object as? DataSource.DataModelType {
                switch source {
                case .AppleCountries:
                    print("AppleCountries")
                case .AppleCountryProvince:
                    print("AppleCountryProvince")
                case .AppleSubRegions:
                    print("AppleSubRegions")
                case .ILINET:
                    print("ILINET")
                case .CDC:
                    print("CDC")
                case .PHL:
                    print("PHL")

                default:
                    print("Default")
                }
            }
        }

问题:我应该在类和启动订阅者的容器视图之间传递一个发布者变量吗?

我了解在同步时间使用 @State <--> @Binding 的原因/影响。
但我需要让视图在获取服务器数据结束时做出异步反应。

我不确定是否可以在容器视图中使用传统的 NSNotification。

底线:我可以让容器视图对网络会话的结束做出反应吗?

标签: asynchronousswiftuicombine

解决方案


推荐阅读