Running one function after another completes

What you need is a completion handler with a completion block.

Its really simple to create one:

func firstTask(completion: (success: Bool) -> Void) {
    // Do something

    // Call completion, when finished, success or faliure
    completion(success: true)
}

And use your completion block like this:

firstTask { (success) -> Void in
    if success {
       // do second task if success
       secondTask()
    }
}

I had a similar situation where I had to init a view once the data is pulled from Parse server. I used the following:

func fetchQuestionBank(complete:()->()){

        let userDefault = NSUserDefaults.standardUserDefaults()
        let username = userDefault.valueForKey("user_email") as? String

        var query = PFQuery(className:"QuestionBank")
        query.whereKey("teacher", equalTo: username!)

        query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in

            if error == nil {
                if let objects = objects as? [PFObject] {

                    var questionTitle:String?
                    var options:NSArray?

                    for (index, object) in enumerate(objects) {

                        questionTitle = object["question_title"] as? String
                        options = object["options"] as? NSArray
                        var aQuestion = MultipleChoiceQuestion(questionTitle: questionTitle!, options: options!)
                        aQuestion.questionId = object.objectId!
                        InstantlyModel.sharedInstance.questionBank.append(aQuestion)
                    }


                    complete()
                }
            }else{
                println(" Question Bank Error \(error) ")
            }
        }
    }

And this is you call the method:

self.fetchQuestionBank({ () -> () in
                        //Once all the data pulled from server. Show Teacher View.
                        self.teacherViewController = TeacherViewController(nibName: "TeacherViewController", bundle: nil)
                        self.view.addSubview(self.teacherViewController!.view)
                    })

You can achieve like this :-

func demo(completion: (success: Bool) -> Void) {
     // code goes here
   completion(success: true)
}

Tags:

Ios

Swift