Alamofire response for base64 string

678 views Asked by At

I am using Alamofire for networking request. It works fine except one issue.

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

}

The server response format is :

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

But I am getting as follow: 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
}

Did I miss something for base64 string? I think it is working before a month but now I am getting issue.

If I make same request via POSTMAN then it works fine!

Thank you,

1

There are 1 answers

0
Roman Podymov On

I can advice you library SwiftyJSON. This library allows you to parse JSON in Swift easily. Also, there is extension AlamofireSwiftyJSON that unites Alamofire and SwiftyJSON. Here is an example for your request:

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