Get response from Moya Response

6.4k views Asked by At

I am using RxSwift and Moya to call request and get response.

My code:

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

It shows something like this:

["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\"}"]

I want to detect the error from this line:

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

When I po response.element?.response?.description, it just give me:

▿ 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} }"

1

There are 1 answers

0
Twitter khuong291 On BEST ANSWER

I have just solved this problem by adding mapJSON() after calling request.

The declaration of mapJSON() is

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

It's description says:

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

My code:

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)