我尝试设置以下方法,一旦执行了所有show.getVideosForShow()成功块并附加了所有视频,就执行成功块。注意:show.getVideosForShow()是异步的,可能需要几秒钟才能得到结果。 有人可以提供一些帮助吗?
private func getNextVideoRecommendations(success: ([Video]) -> ()) {
var relatedVideos = [Video]()
if let relatedShows = self.videoCurrentlyPlaying?.show?.getShowsWithSameGenre(fetchLimit: 3) {
for show in relatedShows {
show.getVideosForShow(tvSeason: nil, longForm: true, sortType: VideoSort.Latest, success: { (videos: [Video]) in
print("Found Related Show: \(show.title)")
if videos.count > 0 {
relatedVideos.append(videos[0])
}
})
}
print("Finished all operations")
success(relatedVideos)
}
}
答案 0 :(得分:4)
这是dispatch groups的一个很好的用例,它允许您在所有操作完成后提交另一个块:
private func getNextVideoRecommendations(success: ([Video]) -> ()) {
var relatedVideos = [Video]()
if let relatedShows = self.videoCurrentlyPlaying?.show?.getShowsWithSameGenre(fetchLimit: 3) {
let group = dispatch_group_create()
for show in relatedShows {
dispatch_group_enter(group) // start tracking one unit of work
show.getVideosForShow(tvSeason: nil, longForm: true, sortType: VideoSort.Latest, success: { (videos: [Video]) in
print("Found Related Show: \(show.title)")
if videos.count > 0 {
relatedVideos.append(videos[0])
}
dispatch_group_leave(group) // finish one unit of work
})
}
dispatch_group_notify(group, dispatch_get_main_queue()) { // and when done...
print("Finished all operations")
success(relatedVideos)
}
}
}