在Alamofire雨燕2.2

问题描述:

早上好使用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) 
     } 
    } 
} 

问候

我会用调度组以SOLV这个问题。使用这些,您可以等待一个或多个进程已完成(超时)。这是一个链接到一个职位进一步的细节。

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

+0

嗨@ Welton122,我试图改变我的代码恩使用调度组,但是,因为我从来没有使用过我有很多问题。你能告诉我一些光吗?我正在尝试按照一些教程和其他练习Stackoverflow,但我无法做到正确。问候。 –

+0

谢谢@ Welton122,我使用调度组,它终于奏效了。 –