【问题标题】:Alamofire response for base64 stringBase64 字符串的 Alamofire 响应
【发布时间】:2023-03-03 07:45:27
【问题描述】:

我正在使用 Alamofire 进行网络请求。除了一个问题,它工作正常。

manager!.request(mutableURLRequest).responseJSON { (response) in
  switch response.result {
        case .Success:
            if let value = response.result.value {
                 print("JSON: \(value)") //**problem**
             }
        case .Failure(let error):
            print(error)
         }

}

服务器响应格式为:

"result" : [
    {
      "rec_name" : "1.jpg",
      "data": {
                "base64": "/9j/4AAQSkZ",
                "__class__": "bytes"
              },
      "id" : 9,
      "name" : "1.jpg"
    },
    {
      "rec_name" : "2.jpg",
      "data": {
                "base64": "/9j/4AAQSkZ",
                "__class__": "bytes"
              },
      "id" : 10,
      "name" : "2.jpg"
    }
  ],
  "id" : 0
}

但我得到如下信息:data(base64 String) is null

"result" : [
    {
      "rec_name" : "1.jpg",
      "data" : null,
      "id" : 9,
      "name" : "1.jpg"
    },
    {
      "rec_name" : "2.jpg",
      "data" : null,
      "id" : 10,
      "name" : "2.jpg"
    }
  ],
  "id" : 0
}

我是否错过了 base64 字符串的某些内容? 我认为它在一个月前可以工作,但现在我遇到了问题。

如果我通过 POSTMAN 发出相同的请求,那么它工作正常!

谢谢,

【问题讨论】:

  • 确保不是你的服务器端改动!!因为如果它以前像你说的那样工作!
  • 向服务器发送请求时,检查是否发送成功。如果已成功发布,则为服务器问题。
  • @Lion,我通过邮递员提出了同样的要求,然后它工作正常!
  • @nirav 你是怎么得到这个输出的?可能您使用了错误的日志格式。或者您是如何检查“数据”是否为空的?
  • @RomanPodymov,我用的是print(response.result.value)

标签: ios iphone alamofire nsurlsession alamofireimage


【解决方案1】:

我可以建议你图书馆SwiftyJSON。这个库允许您在 Swift 中轻松解析 JSON。此外,还有一个扩展 AlamofireSwiftyJSON 将 Alamofire 和 SwiftyJSON 结合在一起。这是您请求的示例:

if let urlToTest = URL.init(string: "your_URL") {

    Alamofire.request(urlToTest,
                      method: .get,
                      parameters: nil,
                      encoding: JSONEncoding.default,
                      headers: nil)
    .responseSwiftyJSON(completionHandler: { (response:DataResponse<JSON>) in

        let jsonResult = response.result
        if let jsonResultValue = jsonResult.value {

            if let resultArray = jsonResultValue["result"].array {

                if resultArray.count > 0 {

                    if let itemData = resultArray[0]["data"].dictionary {

                        if let itemDataBase64 = itemData["base64"]?.string {

                            print("Base 64 field value \(itemDataBase64)")
                        }
                    }
                }
            }
        }
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多