从 Moya Response 获得回应

Get response from Moya Response

我正在使用 RxSwift 和 Moya 调用请求并获得响应。

我的代码:

NetworkManager.shared.request(api: .carrot2diamond, showLoading: false).subscribe({ (response) in
// how to handle with response
}).addDisposableTo(self.disposeBag)

显示如下:

["Moya_Logger: [03/01/2017 16:52:50] Request: http://api.360live.vn/api_shop/carrot2diamond?appversion=1.0&auth_key=f4aeaa8f9df1fd8ef68e1f3e431cd77995d565ef66e7dff9&devid=EA51920A-5C21-41D8-A420-62AF6AAD20FD&platform=2"] ["Moya_Logger: [03/01/2017 16:52:50] Request Headers: [:]"] ["Moya_Logger: [03/01/2017 16:52:50] HTTP Request Method: GET"] ["Moya_Logger: [03/01/2017 16:52:50] Response: { URL: http://api.360live.vn/api_shop/carrot2diamond?appversion=1.0&auth_key=f4aeaa8f9df1fd8ef68e1f3e431cd77995d565ef66e7dff9&devid=EA51920A-5C21-41D8-A420-62AF6AAD20FD&platform=2 } { status code: 200, headers {\n \"Access-Control-Allow-Origin\" = \"*\";\n \"Content-Length\" = 53;\n \"Content-Type\" = \"application/json; charset=utf-8\";\n Date = \"Tue, 03 Jan 2017 09:52:50 GMT\";\n Server = \"Jetty(9.2.z-SNAPSHOT)\";\n
\"X-Server\" = 360Live;\n} }"] ["{\"error\":0,\"message\":\"exchange carrot value invalid\"}"]

我想从这一行检测错误:

["{\"error\":0,\"message\":\"exchange carrot value invalid\"}"]

当我 po response.element?.response?.description 时,它只给我:

▿ Optional - some : " { URL: http://api.360live.vn/api_shop/carrot2diamond?appversion=1.0&auth_key=f4aeaa8f9df1fd8ef68e1f3e431cd77995d565ef66e7dff9&devid=EA51920A-5C21-41D8-A420-62AF6AAD20FD&platform=2 } { status code: 200, headers {\n \"Access-Control-Allow-Origin\" = \"*\";\n \"Content-Length\" = 53;\n \"Content-Type\" = \"application/json; charset=utf-8\";\n Date = \"Tue, 03 Jan 2017 09:52:50 GMT\";\n Server = \"Jetty(9.2.z-SNAPSHOT)\";\n
\"X-Server\" = 360Live;\n} }"

我刚刚通过在调用 request 后添加 mapJSON() 解决了这个问题。

mapJSON()的声明是

func mapJSON(failsOnEmptyData: Bool = default) -> Observable<Any>

它的描述是:

Maps data received from the signal into a JSON object. If the conversion fails, the signal errors.

我的代码:

NetworkManager.shared.request(api: .carrot2diamond, showLoading: false).mapJSON().subscribe({ (response) in
   if let element = response.element, let dic = element as? [String: AnyObject], let message = dic["message"] as? String {
       print(message) // ->>>> exchange carrot value invalid
   }
}).addDisposableTo(self.disposeBag)