如何在task1完成swift后使task2执行?使用dispatch_sync?

时间:2016-05-12 13:22:21

标签: swift swift2

ISSUE:

我有两个任务:task1和task2。我想在task1完成后执行task2。

我的代码:

let globalQueueDefault = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

dispatch_sync(globalQueueDefault){

    self.activityIndicatorView.hidden = false
    self.activityIndicatorView.startAnimating()

        task1()

        sleep(6)
        dispatch_sync(globalQueueDefault) { () -> Void in

            task2()                                             
        }
}

说明

task1应该从互联网上下载一些东西,所以我使用sleep(6)。我认为这个解决方案并不好,因为我们无法确定互联网是否可行。那么在task1结束后你有解决方案向task2发送信号吗?非常感谢你。 !

我的关闭代码就像这样

func getTheSearchLocationAndRange(completed: FinishedDownload) {
    Task1()
    completed()
}
@IBAction func loginAction(sender: AnyObject) {

    getTheSearchLocationAndRange { () -> () in
        Task2()
    }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

如何使用SWIFT CLOSURE:

<强>参考:

请参阅Apple指南:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

示例:

typealias FinishedDownload = () -> ()

override func viewDidLoad() {
    super.viewDidLoad()

    getTheSearchLocationAndRange()
}

func getTheSearchLocationAndRange(completed: FinishedDownload) {

       // Code for searching Location Range HERE

       completed()
}

getTheSearchLocationAndRange { () -> () in
    loadDataFromDatabase()
}

说明:

1)FinishedDownload是关闭。

2)当调用getTheSearchLocationAndRange()时,其代码将执行,直到completed()行等待函数的所有进程完成。

3)一旦进程完成(例如下载),completed()将调用闭包,激活getTheSearchLocationAndRange { () -> () in中定义的代码。

4)因此,loadDataFromDatabase()仅在getTheSearchLocationAndRange()完全执行并且数据存在(不是零)时被调用。

修改

这就是你所做的:

func getTheSearchLocationAndRange(completed: FinishedDownload) {
    Task1()
    completed()
}
@IBAction func loginAction(sender: AnyObject) {

    getTheSearchLocationAndRange { () -> () in
        Task2()
    }
}

这是你应该做的:

typealias FinishedDownload = () -> ()

@IBAction func loginAction(sender: AnyObject) {
    Task1()
}

func Task1(completed: FinishedDownload) {
    //code for Task1
    completed()
}

Task1 { () -> () in
    Task2()
}