top of page
Writer's pictureDi Nerd Apps

Making API Calls with Async/Await in SwiftUI ๐Ÿ‘ฉ๐Ÿฟโ€๐Ÿ’ป๐Ÿง‘๐Ÿฟโ€๐Ÿ’ป

Updated: Mar 25, 2023

Are you tired of making cumbersome API calls in your SwiftUI app? Fear not, because async/await is here to save the day! In this article, weโ€™ll go over how to make API calls using async/await in pure SwiftUI.


First, letโ€™s define what async/await is. Async/await is a new feature in Swift 5.5 that allows you to write asynchronous code in a synchronous style.


It makes your code more readable and easier to write by eliminating the need for completion handlers or delegate callbacks.

Now, letโ€™s dive into the code.


To make an API call using async/await, you first need to define an async function that returns a result. Hereโ€™s an example:

func fetchData() async throws -> [Post] {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode([Post].self, from: data)
}

In this example, we define an async function fetchData that returns an array of Post objects. We use the URLSession API to make a network request and await the response.


Finally, we decode the response data using JSONDecoder.


Now that we have our async function, we can call it from our SwiftUI view. Hereโ€™s an example of how to display a list of posts fetched from an API:

struct ContentView: View {
    @State var posts: [Post] = []

    var body: some View {
        List(posts) { post in
            VStack(alignment: .leading) {
                Text(post.title)
                    .font(.headline)
                Text(post.body)
                    .font(.subheadline)
            }
        }
        .task {
            do {
                posts = try await fetchData()
            } catch {
                print(error.localizedDescription)
            }
        }
    }
}

In this example, we define a ContentView that displays a list of posts fetched from an API. We use the task modifier to call our async function fetchData. If an error occurs, we print the error message to the console.


And there you have it! With just a few lines of code, you can make API calls using async/await in pure SwiftUI.



No more completion handlers or delegate callbacks!

In conclusion, async/await is a powerful tool that can simplify your asynchronous code in SwiftUI. It allows you to write code in a more synchronous style, making it easier to read and write.

Give it a try in your next SwiftUI project and see the difference it makes!




45 views0 comments

Comments


bottom of page