在 Alamofire Swift 2.2 中使用 completionHandler

Using completionHandler in Alamofire Swift 2.2

早上好,

我第一次尝试在 Swift 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)
        }
    }
}

此致

我会使用 Dispatch Groups 来解决这个问题。使用这些,您可以等到一个或多个进程完成(超时)。这是 link 到 post 的详细信息。

http://commandshift.co.uk/blog/2014/03/19/using-dispatch-groups-to-wait-for-multiple-web-services/