The start of one function after another ends

I am trying to run loadViews () after pullData () has completed, and I am wondering what is the best way to do this? I would also like to set a timeout of 10 seconds so that it can display a network error, if possible. From what I read, GCD looks like it's a way to do it, but I'm confused about its implementation. Thanks for any help you can give!

//1 pullData() //2 loadViews() 
+5
source share
3 answers

You need a completion handler with a completion block.

Its really easy to create:

 func firstTask(completion: (success: Bool) -> Void) { // Do something // Call completion, when finished, success or faliure completion(success: true) } 

And use the completion block as follows:

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

I had a similar situation when I had to run the view as soon as the data was retrieved from the 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 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) }) 
+2
source

You can achieve the following: -

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

Source: https://habr.com/ru/post/1242842/


All Articles