【发布时间】:2018-04-06 11:33:01
【问题描述】:
我正在创建一个全局函数来访问 api 并从服务器获取响应。然后该值以类数组的形式返回,但在数据任务之外打印时返回 nil 该值在数据任务内打印
这是我的全局函数代码
func fetchMovieList(url: String ) -> [movies]{
var movie = [movies]()
global.currentUrl = url
// constant to store the url for nowShowing
let convertdUrl = URL(string: url)
// creating a Url session for fetching json from the server
URLSession.shared.dataTask(with: convertdUrl!){(data, response, error) in
// if request is error free then decode the json using json decoder and assigning the values to the array
guard let data = data else {return}
do{
movie = try JSONDecoder().decode([movies].self, from: data)
//movieList.comingSoon = movieList.nowShowing
print("\(movie)")
}catch {
print("Error")
}
}.resume()
print("\(movie)")
return movie
}
【问题讨论】:
-
获取异步完成,因此您无法返回数据。您将需要传递一个闭包来处理它已获取的数据激励
-
我是 swift 新手,如果你能帮助我提供一些我会感谢你的代码
-
定义电影的模型并在该模型中加载值。