watchOS3 handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) on device be called

984 views Asked by At

I found this method be called on the simulator, but on the real watch device, it is never called. Both the apple's simple code and my test.

I want to know is my mistakes or Apple's.

My code -

class InterfaceController: WKInterfaceController, WKExtensionDelegate {


    @IBOutlet var textLbl: WKInterfaceLabel!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        WKExtension.shared().delegate = self

        // Configure interface objects here.
    }

    func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
        for task : WKRefreshBackgroundTask in backgroundTasks {
            if task is WKSnapshotRefreshBackgroundTask {
                textLbl.setText("hahahah");
                task.setTaskCompleted()
            }
        }
    }
}
2

There are 2 answers

0
John Pollard On BEST ANSWER

I managed to find a workaround by pointing the scheduledCompletion attribute to a "real" function rather than a closure e.g.

WKExtension.shared().scheduleBackgroundRefresh(
                  withPreferredDate: nextRefreshTime!, 
                  userInfo: nil, 
                  scheduledCompletion: self.backgroundRefreshRunning)
...

private func backgroundRefreshRunning(error: Error?) {
    if (error != nil) {
        print("Error running background task: \(error.debugDescription)")
    }
}

That now seems to work fine!

My guess is there is a bug in the Swift 3 compiler. I used to use an inline closure for the scheduledCompletion value, which worked fine until I updated my code from Swift 2.3 to Swift 3

1
brunobowden On

The official Apple code example, WatchBackgroundRefresh, also fails in the same way on watchOS 3.0 (14S326). I've also seen the same failure in my own code, though it was working with earlier 3.0 beta version.

Another symptom is that there are no calls to handle(...) for snapshot refresh, i.e. WKSnapshotRefreshBackgroundTask tasks.

I've filed an Apple bug report, which is listed on OpenRader: http://www.openradar.me/radar?id=6720257230110720

Finally, I'd note the Apple Stocks app does get background refreshes. So I'm not sure why that would work whilst other apps would fail.