多个 NSURLSession 依赖的下载任务

Multiple NSURLSession dependent download tasks

我想学习一些 NSURLSession 基础知识,我想知道如何处理来自 API 的多个请求。就像你在 Github 的 api 上请求用户资源一样,它有一个 avatar_url,然后想使用那个 avatar_url 来发出另一个请求。到目前为止我有这个:

let reposEndpoint = URL(string: "users/crystaltwix", relativeTo: baseURL)
        var reposRequest = URLRequest(url: reposEndpoint!)
        reposRequest.allHTTPHeaderFields = [
            "accept": "application/vnd.github.v3+json",
            "content-type": "application/json"
        ]

        session?.dataTask(with: reposRequest) { data, response, error in
            guard let response = response, let data = data else {
                print("something went wrong")
                return
            }
            print("response: \(response)")
            //            print("data: \(data)")
            let decoder = JSONDecoder()
            do {
                let user = try decoder.decode(User.self, from: data)
                print(user)
                // avatar URL
                let avatarURL = URL(string: user.avatarURL)
                let avatarEndpoint = URLRequest(url: avatarURL!)
                self.session?.dataTask(with: avatarEndpoint) { data, response, error in
                    guard let response = response, let data = data else {
                        print("something went wrong inner")
                        return
                    }
                    let avatarImage = UIImage(data: data)
                    let userModel = UserModel(login: user.login, avatar: avatarImage!, name: user.name, bio: user.bio)
                }
            } catch let error {
                print("Error: \(error.localizedDescription)")
                print(error)
                completion(nil, nil, error)
            }
        }.resume()

struct User: Codable {
    let login: String
    let avatarURL: String
    let name: String
    let bio: String

    private enum CodingKeys: String, CodingKey {
        case login
        case avatarURL = "avatar_url"
        case name
        case bio
    }
}

所以对用户的第一个请求有效,我使用 user.avatarURL 使我的 URLRequest 正常,但在下一个

self.session?.dataTask(with: avatarEndpoint) { // nothing happens here }

那里没有请求。处理这种情况的最佳方法是什么?

我看到了你的代码,我想你忘记了在第二个请求中调用 resume 方法。

self.session?.dataTask(with: avatarEndpoint) { data, response, error in
    guard let response = response, let data = data else {
         print("something went wrong inner")
          return
      }
      let avatarImage = UIImage(data: data)
      let userModel = UserModel(login: user.login, avatar: avatarImage!, name: user.name, bio: user.bio)
 }.resume() 

resume方法表示开始请求。