试图理解同步和异步网络调用之间的区别

Trying To Understand the Difference Between Synchronous and Asynchronous Network Calls

我正在尝试弄清楚如何以与进行同步调用相同的方式进行异步网络调用。我想了解我尝试进行的某个网络调用的区别。

这是我发起的同步网络调用:

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()
}

我的主要问题是想弄清楚如何在异步网络调用中正确调用 addValue。

这是我目前的异步调用:

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.")
    }
}

关于包含 addValue,我将如何使异步调用工作?任何帮助将不胜感激。

您可以使用 .data(for: URLRequest) 添加 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.")
        }
    }