Karl
Karl

Reputation: 1621

Handle unknown content-type of response with Alamofire

I use Alamofire to do requests to a rest service. If the request is successful the server returns a JSON with content-type application/json. But if the request fails the server returns a simple String.

So, I don't know how to handle on it with Alamofire, because I don't know how the response look like. I need a solution to handle on the different response types.

This code I can use to handle on a successful request:

request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
            //.validate()
        .responseJSON {
            (request, response, data, error) -> Void in

                //check if error is returned
                if (error == nil) {
                    //this crashes if simple string is returned
                    JSONresponse = JSON(object: data!)
                }

And this code I can use to handle on failed request:

    request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
            //.validate()
        .responseString {
            (request, response, data, error) -> Void in

                //check if error is returned
                if (error == nil) {
                    responseText = data!
                }

Upvotes: 1

Views: 1734

Answers (3)

Derek Soike
Derek Soike

Reputation: 11650

Swift 4

If you are expecting JSON on success and a String on error, you should call the .validate() hook and try parsing the response data as a string if the request fails.

import Alamofire
import SwiftyJSON

...

Alamofire.request("http://domain/endpoint", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
    .validate()
    .responseJSON(completionHandler: { response in
        if let error = response.error {
            if let data = response.data, let errMsg = String(bytes: data, encoding: .utf8) {
                print("Error string from server: \(errMsg)")
            } else {
                print("Error message from Alamofire: \(error.localizedDescription)")
            }
        } 
        guard let data = response.result.value else {
            print("Unable to parse response data")
            return
        }
        print("JSON from server: \(JSON(data))")
    })

Upvotes: 0

Karl
Karl

Reputation: 1621

I've solved my problem:

request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
    .validate()
.response {
    (request, response, data, error) -> Void in

        //check if error is returned
        if (error == nil) {
            var serializationError: NSError?
            let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data! as! NSData, options: NSJSONReadingOptions.AllowFragments, error: &serializationError)

            JSONresponse = JSON(object: json!)
        }
        else {
             //this is the failure case, so its a String
        }
 }

Upvotes: 1

saurabh
saurabh

Reputation: 6775

Don't specify the response type, and don't comment out the .validate(). Check for error, and then proceed accordingly

request(.POST, wholeUrl, parameters: parameters, encoding: .Custom(encodingClosure))
        .validate()
    .response {
        (request, response, data, error) -> Void in

            //check if error is returned
            if (error == nil) {
                //this is the success case, so you know its JSON
                //response = JSON(object: data!)
            }
            else {
                 //this is the failure case, so its a String
            }
     }

Upvotes: 2

Related Questions