几个异步进程作为单个函数调用

时间:2015-12-11 11:03:32

标签: ios swift asynchronous

我需要使用像这样的工作流程在swift中编写一个函数:

  1. 调用ViewController获取数据
  2. 调用Web服务以执行计算
  3. 调用其他网络服务以保留数据
  4. 这三个进程是异步的。

    用户使用以下代码调用此过程:

    <iframe src="{% trans "https://docs.google.com/viewer?embedded=true&amp;url=" %}{{ document.file.url }}" width="451" height="390" style="border: none;"></iframe>

    我应该如何编写流程? 我应该使用GCD吗?

1 个答案:

答案 0 :(得分:1)

您可以使用多个完成处理程序和布尔值来检查每个函数是否已完成如下:

func singleMethodToCall(completion: () -> ()) {
    var methodOneFinished = false
    var methodTwoFinished = false
    var methodThreeFinished = false
    asyncMethodOne { () -> () in
        methodOneFinished = true
        if methodOneFinished && methodTwoFinished && methodThreeFinished {
            completion()
        }
    }

    asyncMethodTwo { () -> () in
        methodTwoFinished = true
        if methodOneFinished && methodTwoFinished && methodThreeFinished {
            completion()
        }
    }

    asyncMethodThree { () -> () in
        methodThreeFinished = true
        if methodOneFinished && methodTwoFinished && methodThreeFinished {
            completion()
        }
    }
}


func asyncMethodOne(completion: () -> ()) {
    //Do Stuff
    completion()
}

func asyncMethodTwo(completion: () -> ()) {
    //Do Stuff
    completion()
}

func asyncMethodThree(completion: () -> ()) {
    //Do Stuff
    completion()
}


singleMethodToCall { () -> () in
    print("All three methods have finishsed")
}
相关问题