0
votes

I'm new to Alamofire, have been trying to work with a web service that I can use through Postman but I can't use via Alamofire. In Postman I can set HTTP Header Key "Accept" with "application/json" and I get a response in Content-Type →application/json; charset=utf-8. However when I try to do the same using Alamofire, the serialization fails cause the response comes in xml. Is there a solution for this? I tried custom HTTP Headers & defaulting session manager with the "Accept" key being set to "application/json" but I can't get the intended response! Here is a sample of the code.

    if let url = URL(string: "http://madinaty.demoday.us/api/1/lookup/stable/") {
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = HTTPMethod.get.rawValue
        urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
        urlRequest.addValue("application/json", forHTTPHeaderField: "accept")

        let request = Alamofire.request(urlRequest)
            .responseJSON{ response  in
                print("Request: \(String(describing: response.request))")  // original URL request
                print("---------------------------")
                print("HTTP URL response: \(String(describing: response.response))") // HTTP URL response
                print("---------------------------")
                print("Data: \(String(describing: response.data))")     // server data
                print("---------------------------")
                print("Result of Reponse Serialization \(response.result)")   // result of response serialization
                print("---------------------------")
                print("Error \(response.result.error)")   // result of response serialization
                print("---------------------------")

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")

                }

        }

This is the error I get:

Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

I also tried this:

        let header = ["content-type" : "application/json"]

    Alamofire.request("http://madinaty.demoday.us/api/1/lookup/stable/",
                      method: .get,
                      parameters: nil,
                      encoding: JSONEncoding.default,
                      headers: header).responseJSON {
                        response in
                        print(response.request)  // original URL request
                        print(response.response) // HTTP URL response
                        print(response.data)     // server data
                        print(response.result)   // result of response

    }

Doesn't work either!

Neither did this work:

                // get the default headers
            var headers = Alamofire.SessionManager.defaultHTTPHeaders
            // add your custom header
            headers["Accept"] = "application/json"

            // create a custom session configuration
            let configuration = URLSessionConfiguration.default
            // add the headers
            configuration.httpAdditionalHeaders = headers

            // create a session manager with the configuration
            let sessionManager = Alamofire.SessionManager(configuration: configuration)

            // make calls with the session manager
            let request = sessionManager.request("http://madinaty.demoday.us/api/1/lookup/stable/")
                .responseJSON { response in
                    debugPrint(response)
                    print("Result of Reponse Serialization \(response.result)")
            }
            debugPrint(request)
2
Add some code, show us what you've done.Simon
@Simon just didTaher
Error Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))Taher

2 Answers

1
votes

After hours of different trials, I finally found the solution for the problem

It turned out that just removing the trailing slash of the URL would solve the problem!

0
votes

Try creating a custom session header configuration:

var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["content-type"] = "application/json"

// custom session configuration
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = headers

let sessionManager = Alamofire.SessionManager(configuration: configuration)

Then make your request using sessionManager.request(...) instead of Alamofire.request(...)