0

我想要实现的是我有一个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"
}
4

1 回答 1

0

我已经在我的许多项目中解析了 api 错误。我相信有更好的选择来处理用户的显示或错误(如果有)。请查看我的代码,如果有错误,我会在祝酒词中显示。在 toast 中显示不是重点,但您可以看到我如何处理代码中的错误情况并且它从未失败过。请根据您的 api 调用更改参数

func postMethod(mylist: [String:Any]) {
    print(K.APIUrl)
    print(K.port)
    AF.request("\(K.urlFromUrlField!):\(K.configPort)/snhttp-01?", method: .put, parameters: mylist)
        .authenticate(username: username, password: password)
        .response { response in
            switch response.result {
            case .success:
                print("\nValidation Successful from put method")
                print(response.result)
                print(response.value as Any)
                
                //get xml code and error msg if any
                
                if let response = response.data{
                    
                    let xml = XML.parse(response)
                    print(xml)
                    print("\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")" )
                    
                    let code = xml.Response.Code.text ?? "No code value in response"
                    let responseMessage = xml.Response.Message.text ?? "No message returned from server"
                    
                    print("\nCode value from server: \(code)")
                    print("\nResponse message from server: \(responseMessage)")
                }
                
                else{
                    print("\nSuccess block: Request Successfully sent, BUT there was nothing from the server to unwrap! / nothing sent back from the server\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")")
                }
                
                
            case let .failure(error):
                
                if let response = response.data {
                    let xml = XML.parse(response)
                    
                    let code = xml.Response.Code.text ?? "\nNo code value in response"
                    let responseMessage = xml.Response.Message.text ?? "No message returned from server"
                    
                    print("\nCode value from server: \(code)")
                    print("\nResponse message from server: \(responseMessage)")
                    print(error)
                    
                }
                
                else    {
                    print("\nFailure Block: A connection to the server could not be established")
                    
                }
                
            }}
    
    }

此代码从 api 解析 xml。但是,您可以放弃它,只关注我如何处理响应以及错误。

于 2021-06-28T06:33:39.127 回答