[英]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: 它的工作方式:
VStack
appears, the model fetch
function is called and executed 出现VStack
,将调用并执行模型fetch
功能 shouldPresentModal
is set to true, and a message is sent down the PassthroughSubject
当请求成功时, shouldPresentModal
设置为true,并在PassthroughSubject
发送消息 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.