user2262304
user2262304

Reputation: 349

How to make task2 execute after task1 finishes in swift ? use dispatch_sync?

ISSUE:

I have two tasks : task1 and task2. I want to execute task2 after task1 finishes.

MY CODE:

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()                                             
        }
}

EXPLANATION:

task1 should download somethings from internet, so I use sleep(6) . I think this solution is not good because we can not be sure the internet will work.. So do you have a solution to send a signal to task2 after the end of task1 ? Thank you very much. !

My code for closure is like this

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

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

Thank you !

Upvotes: 1

Views: 124

Answers (1)

Coder1000
Coder1000

Reputation: 4491

HOW TO USE A SWIFT CLOSURE:

REFERENCE:

Please refer to the Apple guide: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html


EXAMPLE:

typealias FinishedDownload = () -> ()

override func viewDidLoad() {
    super.viewDidLoad()

    getTheSearchLocationAndRange()
}

func getTheSearchLocationAndRange(completed: FinishedDownload) {

       // Code for searching Location Range HERE

       completed()
}

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

EXPLANATION:

1) FinishedDownload is the closure.

2) When getTheSearchLocationAndRange() is called, its code is executed until the completed() line which waits for all processes of the function to finish.

3) Once the processes finish (downloads for example), completed() calls the closure which activates the code defined in getTheSearchLocationAndRange { () -> () in.

4) Therefore, loadDataFromDatabase() is only called once getTheSearchLocationAndRange() has entirely finished executing and the data is present (not nil).

EDIT:

This is what you did:

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

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

This is what you should have done:

typealias FinishedDownload = () -> ()

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

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

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

Upvotes: 2

Related Questions