Making Async Url Calls in Swift 5.5
Async is one of the most requested feature and it’s finally in swift. This simplifies the workflow greatly
Url call
let url = URL(string: "htts://api.github.com/users/hadley/orgs")!
let (data, _) = try await URLSession.shared.data(from: url)
Really its that easy
note that you will need to use this function in an async context only.
Wrapped into async function
func getId() async->Int? {
do {
let url:URL = URL(string: "https://api.github.com/users/hadley/orgs")!
let (data, _) = try await URLSession.shared.data(from: url)
let res:SampleJson = try JSONDecoder().decode([SampleJson].self, from: data)[0]
return res.id
} catch {
debugPrint("\(error)")
return nil
}
}
SwiftUI Example
import SwiftUI
struct ContentView: View {
@State var id_:Int = 0
@State var popUpPresented: Bool = false
var body: some View {
VStack {
Text("\(self.id_)")
.padding()
.font(.title)
// button to trigger refresh
Button("fetch id", role: nil) {
// call get id function
let newId = await self.getId()
// set id and show popup when done
self.id_ = newId ?? 0
self.popUpPresented.toggle()
}
.buttonStyle(.bordered)
}
// show popup if fetch is successful
.popover(isPresented: self.$popUpPresented) {
Text ("url is fetched, id is \(self.id_)")
Button("dissmiss", role: .destructive,action: {self.popUpPresented = false})
.buttonStyle(.bordered)
}
}
func getId() async->Int? {
do {
let url:URL = URL(string: "https://api.github.com/users/hadley/orgs")!
let (data, _) = try await URLSession.shared.data(from: url)
let res:SampleJson = try JSONDecoder().decode([SampleJson].self, from: data)[0]
return res.id
} catch {
debugPrint("\(error)")
return nil
}
}
}
// for decoding the url payload
struct SampleJson: Codable{
let login: String
let id: Int
}
If you are getting ios15 error, just select ios15 target as seen below
Result
with this very simple demo, when you click “fetch id”, the url is fetched and id is displayed as in the picture