-1

I have got a massive and time-consuming routine (calculatePower) that needs a completion handler so that it behaves synchronously. The trigger for the request is a UIButton. It is called in:

func application(application: UIApplication!, performFetchWithCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)!) {
    calculatePower() {
        completionHandler(UIBackgroundFetchResult.NewData)
       }
}

The important bits for the completion handler in calcualtePower reads as:

func calculatePower(completionHandler: (() -> Void)!) {
   completionHandler()
}

Have I got this right and if so do I call application()?

application() 

ain't it.

Edward Hasted
  • 3,201
  • 8
  • 30
  • 48

2 Answers2

1

performFetchWithCompletionHandler is not something that you call. It's something that the runtime calls if you have configured a background download. Your situation doesn't seem to have anything to do with background downloads (does it?) so I'd say you're barking up the wrong tree entirely. If you want to offload a time-consuming calculation to the background, you'd want to learn about GCD and background queues (i.e. dispatch_async). You will easily be able to get back onto the main thread afterwards (with another dispatch_async).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And see my online book: http://www.apeth.com/iOSBook/ch38.html#_grand_central_dispatch – matt Mar 08 '16 at 19:02
0

Solution reads as, many thanks to Matt.

@IBAction func buttonCalculatePower(sender: AnyObject) {
    self.calculateButton.setTitle("Calculating", forState: .Normal)
    self.calculateButton.backgroundColor = UIColor.lightGrayColor()
    self.calculateButton.enabled = false
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            self.calculatePower()
            dispatch_async(dispatch_get_main_queue()) {
                self.calculateButton.backgroundColor = UIColor.orangeColor()
                self.calculateButton.setTitle("Start", forState: .Normal)
                self.calculateButton.enabled = true
        }
    }
}
Edward Hasted
  • 3,201
  • 8
  • 30
  • 48