【问题标题】:Handle unknown content-type of response with Alamofire使用 Alamofire 处理未知内容类型的响应
【发布时间】:2015-05-03 05:22:52
【问题描述】:

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

【问题讨论】:

    标签: ios json swift content-type alamofire


    【解决方案1】:

    不要指定响应类型,也不要注释掉.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(object:data)String?我必须分析响应数据才能在我的代码中执行后续步骤。
    • 您不必分析响应数据,只需检查错误。我已经编辑了答案。
    • 在成功的情况下我做response = JSON(object: data!)。但之后responsenulldata 不为空。
    【解决方案2】:

    我已经解决了我的问题:

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

    【讨论】:

      【解决方案3】:

      斯威夫特 4

      如果您希望 成功 上出现 JSON 并且 错误 上出现 String,则应调用 .validate() 挂钩并尝试将响应数据解析为请求失败时的字符串。

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

      【讨论】:

        猜你喜欢
        • 2020-09-22
        • 1970-01-01
        • 1970-01-01
        • 2012-05-06
        • 1970-01-01
        • 2014-11-15
        • 2018-09-20
        • 2022-08-07
        相关资源
        最近更新 更多