等待多个Alamofire请求完成

时间:2017-10-15 10:31:41

标签: ios swift alamofire

我的网络课程中有一个以下功能来执行Alamofire请求流程。我在我的模型类中调用此函数,当Alamofire完成请求时,它调用委托函数通知模型类。我的问题是我多次调用这个Alamofire函数,两者都应该在通知模型类之前完成。现在我用非常虚拟的方式处理它。在我搜索时,可以使用DispatchGroup,但我无法弄明白,如何实现它。谢谢。

模型类

 @objc func refresh_fiks(){
    let network = Network()
    network.delegate = self
    self.teams = [[]]
    network.getRequest(req: 1)
    network.getRequest(req: 2)

}

请求功能:

    func response(){
    print(response_json.count)
    if(response_json.count == path){
        self.delegate?.sendJson(response_json)
    }
    }
    func getRequest(req: Int) {
    path = req
    let rot = Router(method: .get, path: req, parameters: nil)
    Alamofire.request(rot)
        .response { response in
            print(response.request?.url! as Any)
            // check for errors
            guard response.error == nil else {
                // got an error in getting the data, need to handle it
                print(response.error!)
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                self.response_json.append(errorJson)
                self.response()
                return
            }
            // make sure we got some JSON since that's what we expect
            guard (response.data?.base64EncodedString()) != nil else {
                print("Error: \(String(describing: response.error))")
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                self.response_json.append(errorJson)
                self.response()
                return
            }
            guard response.response?.statusCode == 200 else{
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                self.response_json.append(errorJson)
                self.response()
                return
            }
            let json = JSON(data: response.data!)
            // get and print the title
            if json != nil{
                self.response_json.append(json)
                self.response()
            } else {
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                self.response_json.append(errorJson)
                self.response()
                return
            }
    }
}

1 个答案:

答案 0 :(得分:4)

我对您的代码进行了一些更改:

网络课程:

func response(array: [JSON]){
    print(array.count)
    if(array.count == path){
        self.delegate?.sendJson(array)
    }
}

func getMultipleRequests(_ requests: [Int]) {
    DispatchQueue.global(qos: .background).async {
        let group = DispatchGroup()

        var array: [JSON] = []

        for request in requests {

            group.enter()

            self.getRequest(req: request, completion: { (json) in
                array.append(json)
                group.leave()
            })
        }

        group.wait()
        //this line below won't be called until all entries will leave the group
        self.response(array: array)
    }
}

func getRequest(req: Int, completion: @escaping (_ json: JSON) -> Void) {
    path = req
    let rot = Router(method: .get, path: req, parameters: nil)
    Alamofire.request(rot)
        .response { response in
            print(response.request?.url! as Any)
            // check for errors
            guard response.error == nil else {
                // got an error in getting the data, need to handle it
                print(response.error!)
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                completion(errorJson)
                return
            }
            // make sure we got some JSON since that's what we expect
            guard (response.data?.base64EncodedString()) != nil else {
                print("Error: \(String(describing: response.error))")
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                completion(errorJson)
                return
            }
            guard response.response?.statusCode == 200 else{
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                completion(errorJson)
                return
            }
            let json = JSON(data: response.data!)
            // get and print the title
            if json != nil{
                completion(json)
            } else {
                let errorJson: JSON = [ "Error" : "Can't get the data!"]
                completion(errorJson)
                return
            }
    }
}

所以 getRequest 函数现在有一个完成块,它将返回每个请求的json结果和函数 getMultipleRequests ,它将接收来自任何人的大量请求

这是你如何使用它

你的班级,调用refresh_fiks:

@objc func refresh_fiks(){
    let network = Network()
    network.delegate = self
    self.teams = [[]]

    network.getMultipleRequests([1,2])
}

此外,您可能需要使用 group.wait ,而不是使用 group.wait(),最好通知所有条目都离开了组在指定的队列中,如 main

group.notify(queue: DispatchQueue.main, execute: {
   print("All Done") 
   self.response(array: array)
}) 

阅读有关DispatchGroups的内容:

RayWenderlich

ALL ABOUT SWIFT