我想获取github /用户的数据,然后尝试两种方法:
第一种方法成功:
AF.request("https://api.github.com/users").responseJSON { response in
print("UOUOUOUOUOU", response.description)
}
但是第二秒失败了,为什么?
Network.request(Request.users).responseDecodable { (response: AFDataResponse<UserList>) in
switch response.result {
case .success(let value):
print("SUCCESS")
case .failure(let error):
print("FAIL")
}
}
我需要使用第二种方法。
这是我的班级网络
class Network {
let session: Session
let evaluators = ["api.github.com/users": PinnedCertificatesTrustEvaluator(certificates: [
Certificates.github
])
]
private init() {
session = Session(serverTrustManager: ServerTrustManager(evaluators: evaluators)
)
}
private static let shared = Network()
static func request(_ convertible: URLRequestConvertible) -> DataRequest {
return shared.session.request(convertible)
}
}
我收到此错误:
FAIL serverTrustEvaluationFailed(reason: Alamofire.AFError.ServerTrustFailureReason.noRequiredEvaluator(host: "api.github.com"))
2019-12-17 12:03:21.649222-0400 SSLOwner[5533:83111] Task <57DC5433-F132-4453-BB68-CCF90B5F6058>.<1> HTTP load failed, 0/0 bytes (error code: -999 [1:89])
编辑1:这是我的Struct用户列表和用户
import Foundation
struct UserList: Codable {
let users: [User]
enum CodingKeys: String, CodingKey {
case users = "items"
}
}
struct User: Codable {
let displayName: String
}
与
session = Session()
我收到此错误:
responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(错误:Swift.DecodingError.typeMismatch(Swift.Dictionary,Swift.DecodingError.Context(codingPath:[],debugDescription:“打算解码字典,但找到一个数组代替。”,底层错误:nil)))))]
您的最后一个错误明确指出了错误所在。 API调用的响应是一个数组,而不是您假设的字典。将您的预期响应转换为用户列表,然后应该可以使用:
Network.request(Request.users).responseDecodable { (response: AFDataResponse<[User]>) in
switch response.result {
case .success(let value):
print("SUCCESS")
case .failure(let error):
print("FAIL")
}
}
根对象是一个数组,没有键为items
的对象,因此删除UserList
替换
AFDataResponse<UserList>)
with
AFDataResponse<[User]>)
而且用户词典中也没有键displayName
替换
struct User: Codable {
let displayName: String
}
with
struct User: Codable {
let login: String
}