Dan H Dan H - 5 months ago 145
Swift Question

RX Alamofire Swift empty response JSON

I am using Alamofire with rx and i'm having one issue that if the call is a success (status 200) there is no JSON returned. This triggers my error code. If I get status 400 I get JSON so the call is fine.

How do I specify that the response is JSON, but not to error if empty and status code 200?

Thanks!

func createUser(httpBody: AccountDetails!) -> Observable<(NSHTTPURLResponse, AnyObject)> {

return Alamofire.Manager.rx_request(.POST,
APIService.REGISTER_ENDPOINT,
parameters: httpBody.getParameters(),
encoding: .JSON,
headers: nil)
.flatMap {
$0
.validate(statusCode: 200..<501)
.validate(contentType: ["application/json"])
.rx_responseJSON()
.map { (response:NSHTTPURLResponse, object:AnyObject) -> (NSHTTPURLResponse, AnyObject) in
return (response, object)
}
}
}


EDIT:

I fixed this by changing .rx_responseJSON() to .rx_responseData() and returning NSData instead of AnyObject as the second parameter. Now the call succeeds and I manually convert the data to JSON. Not sure if this is the correct solution but it will suffice for now. Happy to hear better solutions though.
Thanks

Answer

I fixed this by changing .rx_responseJSON() to .rx_responseData() and returning NSData instead of AnyObject as the second parameter. Now the call succeeds and I manually convert the data to JSON. Not sure if this is the correct solution but it will suffice for now. Happy to hear better solutions though. Thanks

func createUser(httpBody: AccountDetails!) -> Observable<(NSHTTPURLResponse, NSData)> {
    return APIManager.sharedManager.rx_request(.POST,
        APIService.REGISTER_ENDPOINT,
        parameters: httpBody.getParameters(),
        encoding: .JSON,
        headers: nil)
        .flatMap {
            $0
                .validate(statusCode: [200,400,500])
                .validate(contentType: ["application/json"])
                .rx_responseData()
            .map { (response:NSHTTPURLResponse, object:NSData) -> (NSHTTPURLResponse, NSData) in
                    return (response, object)
            }
    }
}