Yash R Yash R - 1 month ago 13
Swift Question

How to use JSON objects from root in UIViewController with Alamofire and SwiftyJSON

I want to parse a JSON with Alamofire and SwiftyJSON.

JSON to parse:

"args": {},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-GB,en-US;q=0.8,en;q=0.6",
"Connection": "close",
"Cookie": "_gauges_unique_month=1; _gauges_unique_year=1; _gauges_unique=1",
"Host": "httpbin.org",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
"origin": "",
"url": "http://httpbin.org/get"

I can access the 'args' but I can't access the 'Accept-Encoding' in my

What I am trying in coding:

let Endpoint: String = "http://httpbin.org/get"
Alamofire.request(Endpoint).responseJSON { response in
if let json = response.result.value as? Array<Dictionary<String,Any>> {
self.arrRes = json as [[String:AnyObject]]

I want to use 'Headers' in my

Answer Source

You're trying to cast the json to an array, but it's a dictionary, try this:

let endpoint: String = "http://httpbin.org/get"
Alamofire.request(endpoint).responseJSON { response in
  if let json = response.result.value as? [String:Any],
     let headers = json["headers"] as? [String:Any] {

     self.label.text = headers["Accept-Encoding"] as? String