尝试使用Google Image API在Swift中获取图片网址

时间:2015-03-16 17:14:08

标签: json api swift

我尝试使用带有JSON(https://developers.google.com/image-search/v1/jsondevguide)的Google图片API来获取搜索内容时显示的第一张图片的网址。这就是我所拥有的:

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

responseData部分尽我所能(然后返回所有内容),但尝试更深层次(到#34;结果")会使其崩溃。

1 个答案:

答案 0 :(得分:1)

您将结果声明为字典,但链接的Google页面会显示结果是字典数组的示例。

您可以这样做:

let results = responseData["results"] as [[String:String]]
let firstObject = results[0]
let firstURL = firstObject["unescapedUrl"]