I just completed day 49 of 100 Days of Swift. Today I learnt a lot about Codables, making API requests with URLSession, and validate and disable form data.
Making API requests using a URLSession is actually pretty simple. To do so you first have to create a URL object and then defined the networking task. Here's an example showing you how to do so
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var trackId: Int
var trackName: String
var collectionName: String
}
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
print("Invalid URL")
return
}
let request = URLRequest(url: URL)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.results = decodedResponse.results
}
return
}
}
}.resume()
The code above fetches a list of songs by Taylor swift from the internet. The first thing this code does is to define struct models that represent the JSON being received from the internet. It then creates a URLRquest
using the URL specified.
This URLRequest
is then passed into URLSession.shared.dataTask
in order to make the actual network request. Network requests done by URLSession
are done in a background thread so we need to find a way to send the decoded response from the background thread to the main thread. This is where the DispatchQueue.main.async
comes in. DispatchQueue.main.async
is used to perform a piece of work and send it to the main thread.
Like everything, I've seen so far in SwiftUI validating form is also pretty simple. All you need to do is add a disabled()
modifier. For example, this is how you validate a form in SwiftUI
struct ContentView: View {
@State private var username = ""
@State private var email = ""
var disableForm: Bool {
username.count < 5 || email.count < 5
}
var body: some View {
Form {
Section {
TextField("Username", text: $username)
TextField("Email", text: $email)
}
Section {
Button("Create account") {
print("Creating accountโฆ")
}
}.disabled(disableForm)
}
}
}
The code above defines a SwiftUI view that takes the username and email of a user. Using the disabled modifier on the button's section. That section will be disabled until the both the username and email have more than 5 characters.
Top comments (0)