WKWatchConnectivityRefreshBackgroundTask is never triggered in background, but WKSnapshotRefreshBackgroundTask
Asked Answered
E

2

4

I want to update my watch app state in background from iPhone, using session.updateApplicationContext(applicationContext).

Sending an application contact while the app on the watch is active does work properly.
When I activate the home button on the watch, the watch app goes to the background, handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) is called, and a WKSnapshotRefreshBackgroundTask is provided.

So I don’t understand why a WKSnapshotRefreshBackgroundTask is triggered properly, but not a WKWatchConnectivityRefreshBackgroundTask.

Apple’s docs say „When you receive background data from the paired iPhone, the system launches your app in the background, instantiates a WKWatchConnectivityRefreshBackgroundTask object, and passes the task object to your extension delegate’s handleBackgroundTasks: method.“.

But this does not happen, neither on a device, nor on the simulator. What could be wrong?

Edit:

To check what might be wrong, I downloaded Apple’s demo project „QuickSwitch“ that can be downloaded here. Here is the code that should handle background tasks:

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for backgroundTask in backgroundTasks {
        if let wcBackgroundTask = backgroundTask as? WKWatchConnectivityRefreshBackgroundTask {
            // store a reference to the task objects as we might have to wait to complete them
            self.wcBackgroundTasks.append(wcBackgroundTask)
        } else {
            // immediately complete all other task types as we have not added support for them
            backgroundTask.setTaskCompleted()
        }
    }
    completeAllTasksIfReady()
}

There, the same happens:
I did set a breakponint in the line of the if statement and executed the app.
When the home button on the watch simulator is pressed, the breakpoint is reached with a WKSnapshotRefreshBackgroundTask. This is OK (see above).
However, if a different line is selected on the iPhone simulator, watchOS does not schedule a WKWatchConnectivityRefreshBackgroundTask, as expected. After all, this demo project should demo exactly this point.
Maybe somebody could try the demo project and confirm this problem or not.

What is wrong?

Ecology answered 10/11, 2016 at 21:8 Comment(0)
P
14

Update my answer


Conclusion first

Currently WKWatchConnectivityRefreshBackgroundTask is only called for sure on a watchOS Simulator when the watchOS extension's WCSession is in notActivated state and the extension is not running in foreground (in background or terminated).

In real devices, it won't be called in my tests. But Apple docs says it may. So you shouldn't rely on it won't be called until Apple changes its docs.

WCSession Cores

WCSession Core

For WCSession, when it is activated, you can transfer userInfo, and when the counterpart is active, it can get the userInfo. The counterpart won't need to be in foreground to be activated, it can be in a high priority background.

Testing Results

Here are my testing results.

In Simulators and in devices

How to make WCSession notActivated?

  1. Using Xcode terminate your watchOS Extension. Xcode will send a kill signal to your WKExtension.
  2. Or don't run WCSession.activate() in your code on watchOS Extension side. As WCSession is notActivated by default.

-------------below are old post, you can ignore safely if you don't want to read.-------------------

Theory

enter image description here

Please watch the picture first then I will explain.

Because of the history of watchOS, there are both WCSessionDelegate receiving functions (start from watchOS 2.0) and WKExtensionDelegate.handle(_:) function (start from watchOS 3.0).

Although they all claims to be background dealing, the former only works immediately when your app is in foreground. The data will be queued if your app is not in foreground (in background or being terminated) and executed immediately later when your app becomes in foreground again.

WKExtensionDelegate.handle(_:) is really working in background. However, the WKExtensionDelegate.handle(_:) is optional although it is recommended and well-prepared if you use Xcode.

If you don't implement WKExtensionDelegate.handle(_:) by commenting it. You app works in a watchOS 2.0 way.

If you implement WKExtensionDelegate.handle(_:) but you don't have a WCSession in your watchOS app. The result is tricky. You won't get any data when you watchOS app is in foreground, as you don't has a WCSession. When your app is in background, it will be waken when data comes, but you can't get the data as you don't have a session.

If you implemented them both, which are in most situations, data comes will be dealt depending on the state of your watchOS app and never be queued.


How to proving it?

Create a new watchOS project. In iOS part, add a button, each time you clicked the button, send a userInfo to watchOS

session.transferUserInfo(["send test":""])

In your watchOS app, add a label in interface.storyboard, and drag it to viewController as @IBOutlet var label: WKInterfaceLabel!, and implement both WKExtensionDelegate.handle(_:) and func session(WCSession, didReceiveUserInfo: [String : Any] = [:]) appDelegate.

var total = 0

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
    for task in backgroundTasks {
        // Use a switch statement to check the task type
        switch task {
        case let backgroundTask as WKApplicationRefreshBackgroundTask:
            // Be sure to complete the background task once you’re done.
            backgroundTask.setTaskCompleted()
        case let snapshotTask as WKSnapshotRefreshBackgroundTask:
            // Snapshot tasks have a unique completion call, make sure to set your expiration date
            snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
        case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
            // Be sure to complete the connectivity task once you’re done.
            total += 1
            DispatchQueue.main.async {
                if let viewController = WKExtension.shared().rootInterfaceController as? InterfaceController {
                    viewController.label.setText(String(self.total))
                }
            }

            connectivityTask.setTaskCompleted()
        case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
            // Be sure to complete the URL session task once you’re done.
            urlSessionTask.setTaskCompleted()
        default:
            // make sure to complete unhandled task types
            task.setTaskCompleted()
        }
    }
}

public func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
    total += 4
    DispatchQueue.main.async {
        if let viewController = WKExtension.shared().rootInterfaceController as? InterfaceController {
            viewController.label.setText(String(self.total))
        }
    }
}

If WKExtensionDelegate.handle(_:) runs, we add total by 1. If func session(WCSession, didReceiveUserInfo: [String : Any] = [:]) runs, we add total by 4.

Debug

In Xcode, choose product->scheme as WatchKit app so we can terminate the watchOS app in Xcode.

  1. run the project.
  2. when watchOS app shows, open iOS app manually.
  3. clicked the button in iOS app. You can see the label in watchOS changes by 4.
  4. in Xcode, click product->stop(or cmd+.). watchOS app will disappear.
  5. click one or more times on iOS app's button. Then manually open the watchOS app. You will see this time the label changes by 1 multiply your clicks.
  6. The step will be 4 again when watchOS app is in foreground.
Pollock answered 28/1, 2017 at 22:50 Comment(4)
Thanks a lot for your efforts! I will try it shortly!Araujo
Once again, thank you very much for your detailed answer (+1). I did not yet had time to implement a completely new project as you suggested, but I did the following: In Apple's QuickSwitch demo project, I did remove in session(_ session didReceiveUserInfo) the statement that sets the text in the watch interface controller. So it is no longer set in foreground. I then added such a statement in the handle(_ backgroundTasks) method, hoping that my watch interface would be updated in the background. This is, unfortunately, not the case.Araujo
I agree with your theory but the last paragraph. UserInfo transfer will be queued even if the transfer happens in foreground. However foreground transfer normally happens fast so we do not notice it. In background cases, tasks will definitely being queued. Whenever the app is launched in the backend to receive userInfo depends on when the system sees fit.Mandle
@Mandle The last part, in fact, are unpredictable. I am considering of updating this answer some time this week. In apple's docs, the behavior is describe as "those transfers happen opportunistically in the background". developer.apple.com/reference/watchconnectivity In my test, at least in an apple watch simulator it runs in background. But in physics device it may or may not. session(_:didReceiveUserInfo:) is always called, may in background or in foreground.Pollock
E
1

To all who have the same problem:
I submitted the problem to Apple Developer Technical Support, and they confirmed (# 652471299) the problem in watchOS 3, and suggested to file a bug report, what I did (# 29284559).
So, one has to wait for a bug fix by Apple.

Update:

They answered my bug report, only 2 days later:

Well we get a ton of issues like this, usually it is some misunderstanding about timings or the app not suspending because it is being debugged or not in the dock so it won’t get discretionary tasks.   In this case, reading the description above I’m guessing the user is debugging via xcode while testing.  Two task types: Watch Connectivity and URLSession only arrive as “launch” events.  When debugging, xcode keeps the app running so it will never get these tasks.  The best way to test this is to disconnect from xcode and test, make sure your app is in the dock as well — only docked apps will get discretionary tasks.
If you see this not working after trying that we’ll need a sysdiagnose to go further.

I think this statement is wrong. My reply was:

Thanks for the quick answer. However, something is wrong anyway: The function

handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>)

should handle all background tasks, including WKWatchConnectivityRefreshBackgroundTask.

To check that this is not the case is easy: Just let the app crash when such a background task is scheduled, i.e. insert in Apple’s QuickSwitch demo project an assert statement that is always false:

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for backgroundTask in backgroundTasks {
        if let wcBackgroundTask = backgroundTask as? WKWatchConnectivityRefreshBackgroundTask {
            assert(false) // If the app comes here, it will crash
            // store a reference to the task objects as we might have to wait to complete them
            self.wcBackgroundTasks.append(wcBackgroundTask)
        } else {
            // immediately complete all other task types as we have not added support for them
            backgroundTask.setTaskCompleted()
        }
    }
    completeAllTasksIfReady()
}

Then run the app in foreground, in the dock, or in background, and select different codes on the iPhone. The app will NOT crash, which proves that no WKWatchConnectivityRefreshBackgroundTask is scheduled.
Please do this test without Xcode control. Just run it on iPhone & watch devices.

Now, 1 week later, I did not get any more reply.

Maybe I am wrong, and somebody can give me a hint how to do it right.

Ecology answered 16/11, 2016 at 11:38 Comment(4)
In my own test, I find there is only one way to get the task work. It is remove and reinstall watch app. In iPhone simulator, choose Watch app, uninstall and reinstall your app. Open iOS version of your app, trigger a task, then open the watchOS version of your app, you will see the ran.Pollock
Thanks, Owen, for your comment. Unfortunately, de-installing and re-installing the app does not work for me. I tried it on the simulator and the device, with and without Xcode control. WKWatchConnectivityRefreshBackgroundTask is never called. I tested it with Apple’s QuickSwitch demo project (with the additional assert, see above), WatchOS 3.1.3, iOS 10.2.Araujo
I got the theory and add my answer.Pollock
WatchConnectivity should only work when app is terminated and suspended in the background. Note that simply background the app does not guarantee app being suspended, so to test it, termination is a better shot. Here is the steps: 1. Deploy watch app 2. Open phone app 3. Tap "Stop" in Xcode to terminate watch app 4. Transfer from phone app to watch app 5. Wait. Note there is no promise for an immediate transfer in background case, so you might wait a bit. The time is normally shorter on simulator than device.Mandle

© 2022 - 2024 — McMap. All rights reserved.