异步请求(订单事项)

时间:2017-01-31 04:10:53

标签: asynchronous swift3 grand-central-dispatch alamofire

我正在使用Alamofire同时执行多个异步请求,并使用SwiftyJSON来处理响应。

我需要帮助确保按顺序发生追加moviesByCategory

例如,“top_rated”数据响应应该是附加到moviesByCategory的第一个元素,而不是“即将发布”。

var moviesByCategory = [[JSON]]()    

override func viewDidLoad() {
    super.viewDidLoad()

    let apiEndPoints = ["top_rated", "popular", "now_playing", "upcoming"]
    let dispatchGroup = DispatchGroup()

    for endPoint in apiEndPoints {
        let endPointURL = URL(string: "https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)&language=en-US&page=1")!
        dispatchGroup.enter()
        getMoviesFromEndPoint(url: endPointURL)
    }

    dispatchGroup.notify(queue: DispatchQueue.main) { 
        self.tableView.reloadData()
    }
}

func getMoviesFromEndPoint(url: URL, group: dispatchGroup) {
    Alamofire.request(url).responseData { response in
        if let data = response.result.value {
            let json = JSON(data: data)
            self.moviesByCategory.append(json["results"].arrayValue)
        }
    }
}

DispatchGroup的目的是在所有请求完成后重新加载UITableView

对此的任何帮助都将非常感激。请指出我错在哪里。

1 个答案:

答案 0 :(得分:0)

将完成处理程序参数添加到getMoviesFromEndPoint

func getMoviesFromEndPoint(url: URL, completion: () -> Void) { ... }

并在网络呼叫完成后离开该组:

getMoviesFromEndPoint(url: endPointURL) {
    dispatchGroup.leave()
}

完整代码:

override func viewDidLoad() {
    super.viewDidLoad()

    let apiEndPoints = ["top_rated", "popular", "now_playing", "upcoming"]
    let dispatchGroup = DispatchGroup()

    for endPoint in apiEndPoints {
        let endPointURL = URL(string: "https://api.themoviedb.org/3/movie/\(endPoint)?api_key=\(apiKey)&language=en-US&page=1")!
        dispatchGroup.enter()
        getMoviesFromEndPoint(url: endPointURL) {
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main) {
        self.tableView.reloadData()
    }
}

func getMoviesFromEndPoint(url: URL, completion: () -> Void) {
    Alamofire.request(url).responseData { response in
        if let data = response.result.value {
            let json = JSON(data: data)
            self.moviesByCategory.append(json["results"].arrayValue)                
        }
        completion()
    }
}