0
早上好使用completionHandler,在Alamofire雨燕2.2
我想在雨燕2.2採用completionHandler與Alamofire首次,我有點失去。在我的例子中,我試圖做3個API調用(trakt.tv API),但是我沒有正確地做,因爲completionHandler有一些缺失的值。
我的問題是:我該如何告訴我的函數(帶有completionHandler)等到其他2個函數(getOverview和getPicture)被執行?我嘗試在兩個函數中使用另一個completionHandler,但它不起作用。
這是我的功能:
func getMovies(url: String, clientID: String, completion : ([Movie]) ->()) {
let headers = ["trakt-api-version":"2", "Content-Type": "application/json", "trakt-api-key": clientID]
Alamofire.request(.GET, url, headers: headers).responseJSON { response in
if response.result.isSuccess {
let movieInfo = JSON(data: response.data!)
for result in movieInfo.arrayValue {
let slug = result["ids"]["slug"].stringValue
let title = result["title"].stringValue
let year = result["year"].stringValue
// OVERVIEW
self.getOverview(slug, clientID: clientID) { response in
print("Overview")
print(self.overview)
}
// PICTURE
self.getPicture(slug, clientID: clientID) { response in
print("Picture")
print(self.picture)
}
let movie = Movie(slug: slug, title: title, year: year, overview: self.overview, picture: self.picture)
print("Slug: "+slug)
print("Title: "+title)
print("Year: "+year)
// EMPTY
print("Overview: "+self.overview)
// EMPTY
print("Picture: "+self.picture)
self.movies.append(movie)
}
completion(self.movies)
} else {
print(response.result.error)
}
}
}
這是我的電話:
getMovies(url, clientID: self.clientID) { response in
print(self.movies)
self.tableView.reloadData()
}
這就是我的getOverview功能:
func getOverview(slug: String, clientID: String, completion : (String) ->()) {
let movieURL: String = "https://api.trakt.tv/movies/"+slug+"?extended=full"
let headers = ["trakt-api-version":"2", "Content-Type": "application/json", "trakt-api-key": clientID]
Alamofire.request(.GET, movieURL, headers: headers).responseJSON { response in
if response.result.isSuccess {
let movieInfo = JSON(data: response.data!)
self.overview = movieInfo["overview"].stringValue
completion(self.overview)
} else {
print(response.result.error)
}
}
}
問候
嗨@ Welton122,我試圖改變我的代碼恩使用調度組,但是,因爲我從來沒有使用過我有很多問題。你能告訴我一些光嗎?我正在嘗試按照一些教程和其他練習Stackoverflow,但我無法做到正確。問候。 –
謝謝@ Welton122,我使用調度組,它終於奏效了。 –