我想要实现的是我有一个NetworkManager
处理request
's 到服务器,并通过AFError
. 但是,有时当服务器响应为 4xx 时,会有一条带有该响应的自定义消息,我想向用户展示但不知道如何实现它。
这是我的NetworkManager
static let shared:NetworkManager = {
return NetworkManager()
}()
typealias completionHandler = ((Result<Data, AFError>) ->Void)
func handleAFrequest(request: DataRequest,completion: @escaping completionHandler) {
request.validate(statusCode: 200..<300)
request.responseJSON { (response) in
switch response.result {
case .success(_):
if let data = response.data {
completion(.success(data))
}
case .failure(let error):
print(error.localizedDescription)
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
completion(.failure(.invalidURL(url: URL)))
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription); Reason:\(reason)")
completion(.failure(.responseValidationFailed(reason: reason)))
除了错误之外,我还希望能够投射服务器响应,Message
并向用户显示响应。StatusCode 为 4xx 时的服务器响应示例:
{
"data":
"code":401;
"Message":"Phone Invalid"
}