2017-02-23 36 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