在SwiftUI中使用URLSession请求后如何呈现视图? [英] How to present a view after a request with URLSession in SwiftUI?

查看:61
本文介绍了在SwiftUI中使用URLSession请求后如何呈现视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从请求中接收数据后,我想显示一个视图

I want to present a view after I receive the data from a request, something like this

var body: some View {
          VStack {
            Text("Company ID")
            TextField($companyID).textFieldStyle(.roundedBorder)

            URLSession.shared.dataTask(with: url) { (data, _, _) in
                guard let data = data else { return }

                DispatchQueue.main.async {
                    self.presentation(Modal(LogonView(), onDismiss: {
                        print("dismiss")
                    }))
                }
            }.resume()
        }

    }

推荐答案

将业务逻辑与UI代码混合在一起会带来麻烦.

Business logic mixed with UI code is a recipe for trouble.

您可以按以下方式将模型对象创建为 @ObjectBinding .

You can create a model object as a @ObjectBinding as follows.

class Model: BindableObject {

    var didChange = PassthroughSubject<Void, Never>()

    var shouldPresentModal = false {
        didSet {
            didChange.send(())
        }
    }

    func fetch() {
        // Request goes here
        // Edit `shouldPresentModel` accordingly
    }
}

视图可能类似于...

And the view could be something like...

struct ContentView : View {

    @ObjectBinding var model: Model

    @State var companyID: String = ""

    var body: some View {
        VStack {
            Text("Company ID")
            TextField($companyID).textFieldStyle(.roundedBorder)
            if (model.shouldPresentModal) {
                // presentation logic goes here
            }
        }.onAppear {
            self.model.fetch()
        }
    }
}

工作方式:

  • 出现 VStack 时,将调用并执行模型 fetch 函数
  • 请求成功后, shouldPresentModal 设置为true,并在 PassthroughSubject
  • 下方发送一条消息
  • 作为该主题的订阅者的视图知道模型已更改并触发重新绘制.
  • 如果 shouldPresentModal 设置为true,则会执行其他UI绘制.
  • When the VStack appears, the model fetch function is called and executed
  • When the request succeeds shouldPresentModal is set to true, and a message is sent down the PassthroughSubject
  • The view, which is a subscriber of that subject, knows the model has changed and triggers a redraw.
  • If shouldPresentModal was set to true, additional UI drawing is executed.

我建议观看这场精彩的WWDC 2019演讲:数据通过Swift UI

I recommend watching this excellent WWDC 2019 talk: Data Flow Through Swift UI

以上所有内容都很清楚.

It makes all of the above clear.

这篇关于在SwiftUI中使用URLSession请求后如何呈现视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆