在我的应用中,用户提供了一个电影名称。控制器将从OMDB获得关于该电影的更多信息并存储它。我遇到了将JSON从url转换为字典的问题。这里是我的代码:解析提取的JSON到Swift 3中的字典
@IBAction func addMovieButtonPressed(_ sender: Any) {
// get title from the text field and prepare it for insertion into the url
let movieTitle = movieTitleField.text!.replacingOccurrences(of: " ", with: "+")
// get data for the movie the user named
let movieData = getMovieData(movieTitle: movieTitle)
// debug print statement
print(movieData)
// reset text field for possible new entry
movieTitleField.text = ""
}
// function that retrieves the info about the movie and converts it to a dictionary
private func getMovieData(movieTitle: String) -> [String: Any] {
// declare a dictionary for the parsed JSON to go in
var movieData = [String: Any]()
// prepare the url in proper type
let url = URL(string: "http://www.omdbapi.com/?t=\(movieTitle)")
// get the JSON from OMDB, parse it and store it into movieData
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
movieData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
} catch let error as NSError {
print(error)
}
}).resume()
// return the data
return movieData
}
我已经试过,我#2发现URLSession部分的许多变化,我知道的数据是成功读取:
但是我不知道如何正确地把它变成一本字典,然后我可以在我的应用程序的其余部分使用它。 IBAction函数中的print语句总是返回一个空字典。
我在做什么错?
http://stackoverflow.com/q/40810108/2976878的可能的复制 - HTTP:// stackoverflow.com/q/40014830/2976878 - http://stackoverflow.com/q/27081062/2976878 - http://stackoverflow.com/q/31264172/2976878 - http://stackoverflow.com/q/25203556/ 2976878 – Hamish