Alamofire requests with response type of text/html

Viewed 793

I am converting an Objective C project into swift and as a result, I need to use Alamofire instead of AFNetworking. The server I need to make HTTP calls to expects parameters in JSON format but responds in text/html. When I test the requests in Objc, it works but on swift and alamofire, the response data is nil. I have done this previously using AFNetworking responseSerializer and set the acceptable content types to all 4 possible types. I just can't seem to make this work with Alamofire. I have used any help and tutorials out there but I am banging my head to the ceiling each time. Te errors I get are usually Unable to determine byte size or responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength.

Here is sample code I have used so far:

let urlString = "\(K.APIKs.kInsecureProtocol)\(K.APIKs.KBaseURL)\(K.APIKs.kSignupURL)"
        let parameters: Parameters = [K.SignUPKs.kMSISDN: number]

        AF.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default).responseJSON { (response) in

            switch response.result {
            case .success:
                self.authorisingSignUpDelegate?.onAuthorisingSignUpSuccess()
                break

            case .failure(let error):
                self.authorisingSignUpDelegate?.onAuthorisingSignUpFailed(error: error)
                break

            }
        }

then tried setting the acceptable content types:

if let url = URL(string: urlString) {
            var urlRequest = URLRequest(url: url)
            urlRequest.httpMethod = HTTPMethod.post.rawValue
            urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
            urlRequest.addValue("text/html", forHTTPHeaderField: "accept")
            urlRequest.httpBody =  try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

            let request = AF.request(urlRequest)
                .response { 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.error)")   // result of response serialization
                print("---------------------------")

                print("JSON: \(response.result)")
                }
}

None of the methods I have tried work. Can anyone help me please? Thanks a million!

1 Answers

For those who'd have a similar problem, I wrote the fix as follow:

if let returnedData = JSONData {
                    do {
                        let dict =  try JSONSerialization.jsonObject(with: returnedData, options: []) as? [String: String]
                        DataManager().synchronisePassword(from: dict!)

                    } catch {
                        print(error.localizedDescription)
                    }
                }
Related