2017-02-23 131 views
1

在我的应用中,用户提供了一个电影名称。控制器将从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部分的许多变化,我知道的数据是成功读取:
screenshot

但是我不知道如何正确地把它变成一本字典,然后我可以在我的应用程序的其余部分使用它。 IBAction函数中的print语句总是返回一个空字典。

我在做什么错?

+0

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

回答

2

查看完成块和异步函数。您的getMovieData在调用datatask完成处理程序之前正在返回。

你的功能,而不是返回,将调用完成块的传入和应更改为:

private func getMovieData(movieTitle: String, completion: @escaping ([String:Any]) -> Void) { 

    // 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] 
      completion(movieData) 
     } catch let error as NSError { 
      print(error) 
     } 
    }).resume() 
} 
+1

啊!我现在知道了。这是我没有想到自己的方向。我将研究异步函数是如何工作的,研究如何写出完成时调用的函数以及如何调用这个异步函数。谢谢! – stfwn