I am trying to figure how I can make an asynchronous network call in the same way that I am doing a synchronous call. I want to understand the difference with regards to a certain network call I am trying to make.
This is the synchronous network call I made:
func fetchTrendingMoviesSynchronous() {
guard let url = URL(string: "https://api.trakt.tv/movies/trending") else {
print("Could not get trending movies.")
return
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("2", forHTTPHeaderField: "trakt-api-version")
request.addValue("My_API_Key", forHTTPHeaderField: "trakt-api-key")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if response != nil {
if let decodedResponse = try? JSONDecoder().decode([TrendingMovie].self, from: data!) {
print("We got the trending movies.")
trendingMovies = decodedResponse
}
} else {
print("Could not get trending movies.")
}
}
task.resume()
}
My main issue is trying to figure out how to call addValue properly in the asynchronous network call.
This is what I have so far for the asynchronous call:
func fetchTrendingMoviesAsynchronous() async {
guard let url = URL(string: "https://api.trakt.tv/movies/trending") else {
print("Could not get trending movies.")
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let decodedResponse = try? JSONDecoder().decode([TrendingMovie].self, from: data) {
print("We got the trending movies.")
trendingMovies = decodedResponse
}
} catch {
print("Could not get trending movies.")
}
}
How would I go about making the asynchronous call work with regards to including addValue
? Any help would be greatly appreciated.
CodePudding user response:
You can use .data(for: URLRequest)
in order to add headers.
func fetchTrendingMoviesAsynchronous() async {
guard let url = URL(string: "https://api.trakt.tv/movies/trending") else {
print("Could not get trending movies.")
return
}
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("2", forHTTPHeaderField: "trakt-api-version")
request.addValue("My_API_Key", forHTTPHeaderField: "trakt-api-key")
do {
let (data, _) = try await URLSession.shared.data(for: request)
if let decodedResponse = try? JSONDecoder().decode([TrendingMovie].self, from: data) {
print("We got the trending movies.")
trendingMovies = decodedResponse
}
}catch {
print("Could not get trending movies.")
}
}