Search code examples
jsonswiftalamofire

Swift: JSON is nil when accessing NSDictionairy


When I print(JSON) I get the files, so the .request works. But when I am trying to access the "test" key (which exists) I get nil

I get

"I am here"
"now ,I am here"

Alamofire.request(.GET, self.APIBaseUrl , parameters: ["api_key": self.APIkey])
            .responseJSON { response in
                if let JSON = response.result.value {
                  print("I am here")
                  if let str = JSON as? NSDictionary {
                     print("now , I am here")
                     if let movieUrlString = str["poster_path"] as? String)! {
                        print("but now here")
                        }

EDITED

print(dict)


**dates** =     {
maximum = "2015-10-21";
minimum = "2015-09-30";
};
page = 1;
**results** =     (
            {
 adult = 0;
"poster_path" = "/2XegKZ0I4QrvzpEHneigRk6YTB1.jpg";

++(more results)


Solution

  • Try to use more meaningful debug printing statements and variables names. Also you were not using the right variable for subscripting. Fixed example:

    Alamofire.request(.GET, self.APIBaseUrl , parameters: ["api_key": self.APIkey]).responseJSON { response in
        if let JSON = response.result.value {
            print("inside JSON result")
            if let dict = JSON as? NSDictionary {
                print("inside decoded JSON")
                if let results = dict["results"] as? [NSDictionary] {
                    for result in results {
                        if let movieUrlString = result["poster_path"] as? String {
                            print(movieUrlString)
                        }
                    }
                }
            }
        }
    }