1

例如,我可以访问“字典”moviedb:https ://www.themoviedb.org/search/remote/multi?query=exterminador%20do%20futuro&language=en

我如何才能在 Swift 的项目中只从这个页面捕捉到电影的名称和海报?

4

2 回答 2

1

这是答案:)

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        reload()
    }

    private func reload() {
        let requestUrl = "https://www.themoviedb.org/search/remote/multi?query=exterminador%20do%20futuro&language=en"

        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)
        let request = NSURLRequest(URL: NSURL(string: requestUrl)!)

        let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                println("###### error ######")
            }
            else {
                if let JSON = NSJSONSerialization.JSONObjectWithData(data,
                    options: .AllowFragments,
                    error: nil) as? [NSDictionary] {

                        for movie in JSON {
                            let name = movie["name"] as! String
                            let posterPath = movie["poster_path"] as! String

                            println(name)        // "Terminator Genisys"
                            println(posterPath)  // "/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg"
                        }
                }
            }
        })

        task.resume()
    }
}
于 2015-07-29T13:26:50.153 回答
0

您需要在请求中包含您的 api 密钥。我只是尝试这样的事情,看看它是否有效。如果是这样,那么您可以以不同的方式使用 api 密钥以使其更安全。我不会打扰,因为它不是具有非常敏感功能的 api。

let query = "Terminator+second"
let url = NSURL(string: "http://api.themoviedb.org/3/search/keyword?api_key=YOURAPIKEY&query=\(query)&language=‌​en")!
let request = NSMutableURLRequest(URL: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
    if let response = response, data = data {

    print(response)

    //DO THIS
    print(String(data: data, encoding: NSUTF8StringEncoding))

    //OR THIS
    if let o = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:nil) as? NSDictionary {
        println(dict)
    } else {
        println("Could not read JSON dictionary")
    }
} else {
    print(error)
}
}

task.resume()

您将获得的响应将包含完整的属性列表。您需要返回项目的 poster_path 和 title(或 original_title)属性。

于 2016-03-27T19:50:38.440 回答