如何在swift 4中进行两个并发API调用

时间:2018-05-27 23:32:30

标签: ios swift4 nsoperationqueue nsoperation swift4.1

先谢谢你的帮助, 我有两个API调用,两者都是并发的,任何调用都可以成功(我不想按顺序调用),两次调用成功后,我必须停止我的活动指示器并重新加载我的tableView, 这是我的代码,但我不知道这是否正确以及如何重新加载我的tableView并停止我的活动指示器。

func downloadDetails(){
    let operationQueue: OperationQueue = OperationQueue()
    let operation1 = BlockOperation() {
    WebServiceManager.getAData(format:A, withCompletion: {(data: Any? , error: Error?) -> Void in

          if let success = data {
              DispatchQueue.main.async {
                  (success code)
              }
           }
        })

        let operation2 = BlockOperation() {
        webServiceManager.getBData(format: B, withCompletion: {(data: Any? , error: Error?) -> Void in

                if let success = data {
                    DispatchQueue.main.async {
                       (success code)
                    }
                }
            })
        }
        operationQueue.addOperation(operation2)
    }
    operationQueue.addOperation(operation1)
}
downloadDetails() "calling function"

3 个答案:

答案 0 :(得分:12)

这正是DispatchGroup的用例。输入每个呼叫的组,在呼叫结束时离开组,并在完成所有操作后添加通知处理程序。不需要单独的操作队列;这些都是异步操作。

func downloadDetails(){
    let dispatchGroup = DispatchGroup()

    dispatchGroup.enter()   // <<---
    WebServiceManager.getAData(format:A, withCompletion: {(data: Any? , error: Error?) -> Void in

        if let success = data {

            DispatchQueue.main.async {
                (success code)
                dispatchGroup.leave()   // <<----
            }
        }
    })

    dispatchGroup.enter()   // <<---
    webServiceManager.getBData(format: B, withCompletion: {(data: Any? , error: Error?) -> Void in

        if let success = data {

            DispatchQueue.main.async {
               (success code)
               dispatchGroup.leave()   // <<----
            }
        }
    })

    dispatchGroup.notify(queue: .main) {
        // whatever you want to do when both are done
    }
}

答案 1 :(得分:0)

如何拥有2个布尔变量,每个请求一个。第一个成功代码设置为其中一个变量,另一个成功代码设置为第二个。

在停止活动指示器和刷新tableview之前,检查功能应检查两个变量是否为真。

var success1 = false
var success2 = false

//For the first api call
DispatchQueue.main.async {
    success1 = true
    successCode()
}

//For the second api call
DispatchQueue.main.async {
    success2 = true
    successCode()
}

func successCode() {
    if ((success1 == true) && (success2 == true)) {
        activityIndicator.stopAnimating()
        tableView.reloadData()
    }
}

答案 2 :(得分:0)

我会使用OperationQueue。

对于长时间运行的任务,如果需要,可以控制取消请求。

在每个操作结束时,您可以检查操作计数以了解剩余操作。

我添加了伪代码。

let operationQueue: OperationQueue = OperationQueue()

func downloadDetails(){

    let operation1 = BlockOperation() { [weak self] in

        guard let strongSelf = self else {
            return
        }

        sleep(2)

        DispatchQueue.main.async {
            strongSelf.handleResponse()
        }

        let operation2 = BlockOperation() { [weak self] in

            guard let strongSelf = self else {
                return
            }

            sleep(2)

            DispatchQueue.main.async {
                strongSelf.handleResponse()
            }
        }
        strongSelf.operationQueue.addOperation(operation2)
    }

    self.operationQueue.addOperation(operation1)
}

func handleResponse() {
    print("OPERATIONS IN PROGRESS: \(self.operationQueue.operations.count)")
    if self.operationQueue.operations.count == 0 {
        print("ALL OPERATIONS ARE COMPLETE")
    }
}

func cancelOperation() {
    self.operationQueue.cancelAllOperations()
}

打印

OPERATIONS IN PROGRESS: 1
OPERATIONS IN PROGRESS: 0
ALL OPERATIONS ARE COMPLETE