Skip to main content
 首页 » 操作系统

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

2024年01月01日49duanxz

我使用 Alamofire 向休息服务发出请求。如果请求成功,服务器将返回内容类型为 application/json 的 JSON。但如果请求失败,服务器将返回一个简单的 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 
            } 
     }