在我的應用中,用戶提供了一個電影名稱。控制器將從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