SwiftUI Journey Part 6: Async/Await with SwiftUI

Posted on May 17, 2022

Today I learned how to call async/await functions with SwiftUI. This has the same flow with the sign in page but this one is using concurrency. On that note, I need to refactor the sign in page to use concurrency.

import SwiftUI
struct MainView: View  {
@State private var signInSuccess = false
    
    var body: some View {
        if signInSuccess {
            HomeView()
        } else {
            VStack {
                Image("OnlineJobs Logo")
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 50, height: 30)
                    .padding(.bottom, 50)
            }
            .frame(minWidth: 500, maxWidth: .infinity, minHeight: 300, maxHeight: 800)
            .background(Color(red: 2 / 255, green: 69 / 255, blue: 112 / 255))
            .task {
                await checkLoginStatus()
            }
        }
    }
}

Take note of the .task{} code block, this is the place to call your async function.

My async function looks like this

private func checkLoginStatus() async {
if let url = URL(string: Urls.main.employerJobs) {
                var request = URLRequest(url: url)
                request.httpMethod = "GET"
                do {
                    let (_, response) = try await URLSession.shared.data(for: request)
                    if let responseURL = response.url {
                        if responseURL.absoluteString.contains(Urls.main.employerJobs) {
                            signInSuccess = true
                        }
                    }
                } catch {
                    signInSuccess = false
                }
            }
}

When the server response URL matches the condition then signInSuccess = true is called. And this will then change the layout to HomeView().