使用 Alamofire 处理未知内容类型的响应

Handle unknown content-type of response with Alamofire

我使用 Alamofire 来请求休息服务。如果请求成功,服务器 returns 内容类型为 application/jsonJSON。但是如果请求失败服务器 returns 一个简单的 String.

所以,我不知道如何用 Alamofire 处理它,因为我不知道响应是什么样子的。我需要一个解决方案来处理不同的响应类型。

我可以用来处理成功请求的代码:

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!)
                }

我可以用这段代码来处理失败的请求:

    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!
                }

不要指定响应类型,也不要注释掉 .validate()。 检查错误,然后相应地进行

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

我已经解决了我的问题:

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

Swift 4

如果您期望 JSON 成功 String 错误,您应该调用.validate() hook 并尝试在请求失败时将响应数据解析为字符串。

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