Tom Miller
Tom Miller

Reputation: 53

SwiftUI how can I make my app pause until I receive some API Data?

import SwiftUI

struct LoginView: View {
    @ObservedObject var vm : ViewModel
    @State private var username = ""
    private var searchAllowed : Bool{
        if(username.count>2)
        {
            return false
        }
        return true
    }
    
    
    var body: some View {
        NavigationView{
            VStack{
                Text("Enter your Username:")
                    .font(.title.bold())
                
                
                TextField("Username", text: $username)
                    .frame(width: 280)
                    .padding(.bottom)
                
                
                NavigationLink{
                    ProfileView(vm: vm)
                } label:
                {
                    ZStack{
                        RoundedRectangle(cornerRadius: 5)
                            .fill(.gray)
                            .frame(width: 200, height: 50)
                        
                        Text("Search")
                            .foregroundColor(.white)
                            .task {
                                await vm.fetchPlayerData()
                            }
                        
                    }
                }
                .disabled(searchAllowed)
            }
            
        }
    }
    
}

So I want it so that when I press the search NavigationLink it'll only take me to the view if the api call was sucessful and I got some particular piece of data I needed.

How can I make it conditional like this? It's all sync so it seems like I can't really wait to see if I have the right data before moving the user into the new View.

Upvotes: 0

Views: 181

Answers (1)

Berhtulf
Berhtulf

Reputation: 81

As @NoeOnJupiter said:

In your NavigationLink destination, use conditional view logic, that shows ProgressView. After your loadData() finishes, flip a boolean and show your desired View showing API Data.

Upvotes: 2

Related Questions