【问题标题】:Parsing fetched JSON to dictionary in Swift 3在 Swift 3 中解析获取的 JSON 到字典
【发布时间】:2017-07-14 12:16:20
【问题描述】:

在我的应用中,用户有时会提供电影名称。控制器将从OMDB 获取有关电影的更多信息并将其存储。我在将 JSON 从 url 转换为字典时遇到问题。这是我的代码:

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

我已经尝试了我在 Stackoverflow 上找到的 URLSession 部分的许多变体,并且我知道数据已成功获取:

但是我不知道如何正确理解它并将其转换为字典,然后我可以在我的应用程序的其余部分中使用它。 IBAction 函数中的 print 语句总是返回一个空字典。

我做错了什么?

【问题讨论】:

标签: swift nsurlsession


【解决方案1】:

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

您的函数将调用传入的完成块,而不是返回,并应更改为:

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

【讨论】:

  • 啊!我现在知道了。这是我自己没有想到的方向。我将研究异步函数是如何工作的,弄清楚如何写出完成时调用的函数以及如何调用这个异步函数。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2018-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多