Use NavigationButton with a server request in SwiftUI

后端 未结 1 951
轮回少年
轮回少年 2021-01-06 05:45

How can I make a NavigationButton to wait for the server response before going to the next view ?

I\'ve tried something like this

Naviga         


        
相关标签:
1条回答
  • 2021-01-06 06:43

    Sorin, at least in my understanding SwiftUI is designed only for the presentation layer, it's not supposed to replace your model. And it's "reactive", unlike UIKit, so making the view perform model-like actions is, by design, very hard.

    I would approach the task like this :

    class LoginModel : BindableObject {
    
        var didChange = PassthroughSubject<LoginModel, Never>()
    
        private(set) var username: String? {
            didSet {
                didChange.send(self)
            }
        }
    
        func load() {
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                self.username = "Sorin"
            }
        }
    }
    

    This is the model object encapsulating our login code. The async operation is here simulated by a simple delay.

    And, then, the view :

    public struct LoginScreen: View {
    
        @ObjectBinding var loginObject = LoginModel()
    
        public var body: some View {
            Group {
                if login.username == nil {
                    Text("Trying to login, please wait...")
                } else {
                    Text("Successful login, the username is \(loginObject.username!)")
                }
            }.onAppear {
                self.loginObject.load()
            }
        }
    }
    

    There are better ways of "linking" with the model object, but we're looking here only at a bare-bone example, obviously.

    Your NavigationButton will only link to the LoginScreen, without any other code or trigger. The screen will initially display Trying to login, please wait... and after 5 sec will change to Successful login, the username is Sorin. Obviously you could go wild and replace my text here with anything you may want.

    0 讨论(0)
提交回复
热议问题