使用Alamofire处理未知内容类型的响应
问题描述:
我使用Alamofire
来处理对休息服务的请求。如果请求成功,则服务器返回JSON
,内容类型为application/json
。但是如果请求失败,服务器将返回一个简单的String
。使用Alamofire处理未知内容类型的响应
所以,我不知道如何处理它与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!
}
答
我已经解决了我的问题:
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
}
}
答
不要指定响应类型,并且不要评论出.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
}
}
我试过,但我怎么能转换'data'到'JSON(对象:数据) '或'字符串'?我必须分析响应数据才能执行代码中的下一步。 – Karl 2015-03-02 19:45:53
您不必分析响应数据,只需检查错误。我编辑了答案。 – sasquatch 2015-03-02 19:58:54
在成功案例中,我做了'response = JSON(object:data!)'。但是'response'在那之后是'null'。数据不为空。 – Karl 2015-03-06 10:25:40