我想学习一些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 }
那里没有请求。处理这种情况的最佳方法是什么?
答案 0 :(得分:0)
我看到你的代码,我想你忘了在第二次请求中调用resume方法。
git add -A
git commit
resume方法意味着开始请求。