1

I'm trying to use the google image API with JSON (https://developers.google.com/image-search/v1/jsondevguide) to get the URL of the first image that shows when searching something. This is what I have:

let placeName = "New York"

func getImage() {
    let url = NSURL(string: "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=\(placeName)")
    let request = NSURLRequest(URL: url!)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){ (response, go, error) -> Void in
    let go = NSJSONSerialization.JSONObjectWithData(go, options: NSJSONReadingOptions.AllowFragments, error: nil) as [String:AnyObject]
        let responseData = go["responseData"] as [String:AnyObject]
        // let results = responseData["results"] as [String:AnyObject]
        // let imageURL = results["unescapedUrl"] as String
        println(responseData)
}
}

The responseData part is as far as I can go (that then returns everything), but trying to go one level deeper (to "results") will crash it.

1
  • 1
    I suggest you use alamofire and SwiftyJson. Commented Mar 17, 2015 at 6:30

1 Answer 1

1

You declare results as a dictionary but your linked Google page shows an example where results is an array of dictionaries.

You can do this instead:

let results = responseData["results"] as [[String:String]]
let firstObject = results[0]
let firstURL = firstObject["unescapedUrl"]
Sign up to request clarification or add additional context in comments.

1 Comment

knew it would be a simple fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.