简体   繁体   English

如何在SwiftUI中使用URLSession请求后显示视图?

[英]How to present a view after a request with URLSession in SwiftUI?

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()
        }

    }

Business logic mixed with UI code is a recipe for trouble. 与UI代码混合的业务逻辑是一个麻烦的方法。

You can create a model object as a @ObjectBinding as follows. 您可以将模型对象创建为@ObjectBinding ,如下所示。

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()
        }
    }
}

The way it works: 它的工作方式:

  • When the VStack appears, the model fetch function is called and executed 出现VStack ,将调用并执行模型fetch功能
  • When the request succeeds shouldPresentModal is set to true, and a message is sent down the PassthroughSubject 当请求成功时, shouldPresentModal设置为true,并在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. 如果shouldPresentModal设置为true,则执行其他UI绘图。

I recommend watching this excellent WWDC 2019 talk: Data Flow Through Swift UI 我建议观看这个优秀的WWDC 2019演讲: 数据流通过Swift UI

It makes all of the above clear. 它使以上所有都清楚。

I think you can do smth like that: 我想你可以这样做:

var body: some View {
        VStack {
            Text("Company ID")
        }
        .onAppear() {
            self.loadContent()
        }
    }

    private func loadContent() {
        let url = URL(string: "https://your.url")!
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }
            DispatchQueue.main.async {
                self.presentation(Modal(ContentView(), onDismiss: {
                    print("dismiss")
                }))
            }
            }.resume()
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM