【问题标题】:Connection <number>: unable to determine fallback status without a connection连接 <number>:无法在没有连接的情况下确定回退状态
【发布时间】:2021-07-10 14:07:57
【问题描述】:

使用结合而不是闭包的 API。使用 URLSession 任务和 .resume 获取带有闭包的资源不会出错,而使用 Combine 获取会给出:

Connection 57: unable to determine fallback status without a connection
struct Item: View {
    @ObservedObject var item: Item
    @State var thumbnail: UIImage?
    
    var body: some View {
        NavigationLink(destination: ItemView(item: item, thumbnail: thumbnail)) {
            ItemRowView(item: item, thumbnail: thumbnail)
        }
        .onAppear {
             let url = URL(string: "valid address")!
             let cancellable = URLSession.shared.dataTaskPublisher(for: url)
                 .receive(on: DispatchQueue.main)
                 .sink(receiveCompletion: { print ("Received completion: \($0).") },
                       receiveValue: { print ("Received data: \($0.data).")})
        }
    }
}

Unable to determine interface type without an established connection Xcode 也有类似的问题。但是,在我的情况下不应该有任何 TLS 错误,因为端点有一个有效的证书并且在没有组合的情况下可以正常工作。

由于不清楚缺少什么回退状态以及为什么没有连接,您能否解释一下错误本身?

【问题讨论】:

    标签: ios swift swiftui combine


    【解决方案1】:

    似乎cancellable 必须分配给视图的状态变量,如下所示:

    struct Item: View {
        @ObservedObject var item: Item
        @State var thumbnail: UIImage?
        @State var cancellable: AnyCancellable?
        
        var body: some View {
            NavigationLink(destination: ItemView(item: item, thumbnail: thumbnail)) {
                ItemRowView(item: item, thumbnail: thumbnail)
            }
            .onAppear {
                 let url = URL(string: "valid address")!
                 cancellable = URLSession.shared.dataTaskPublisher(for: url)
                     .receive(on: DispatchQueue.main)
                     .sink(receiveCompletion: { print ("Received completion: \($0).") },
                           receiveValue: { print ("Received data: \($0.data).")})
            }
        }
    }
    

    否则请求不会被执行。

    【讨论】:

    • 虽然有可能,但您应该避免直接在视图中执行逻辑和调用具有副作用(网络请求)的任务。将逻辑和网络代码移动到某个视图模型或模型,并为视图提供一个值,该值表示其要呈现的内容。这样,您可以减少视图中的复杂代码,避免不必要的 @State 变量,防止 body 中的无效递归导致运行时错误,获得更好的性能(@State 很慢)并获得可测试性。
    • @CouchDeveloper,感谢您的评论
    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 2014-04-14
    • 2012-07-11
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多