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.
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()
}
}
}
The way it works:
VStack
appears, the model fetch
function is called and executedshouldPresentModal
is set to true, and a message is sent down the PassthroughSubject
shouldPresentModal
was set to true, additional UI drawing is executed.I recommend watching this excellent WWDC 2019 talk: Data Flow Through Swift UI
It makes all of the above clear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With