WKWatchConnectivityRefreshBackgroundTask is never triggered in background, but WKSnapshotRefreshBackgroundTask - background-task

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?

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
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.
How to make WCSession notActivated?
Using Xcode terminate your watchOS Extension. Xcode will send a kill signal to your WKExtension.
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
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.
run the project.
when watchOS app shows, open iOS app manually.
clicked the button in iOS app. You can see the label in watchOS changes by 4.
in Xcode, click product->stop(or cmd+.). watchOS app will disappear.
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.
The step will be 4 again when watchOS app is in foreground.

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.

Related

Updating Live Activities without using push notifications

I have a progress indicator in the Live Activity that should update every 15 minutes. I know that the way to go is using Push Notifications but they are not an option for me.
I have seen Apps on the Appstore and even the native timer update their live activities when push notifications are not enabled and even background App fetch is disabled.
In Apple's docs, it is mentioned that you can update or end a Live Activity from your app while it runs in the background — for example, by using Background Tasks.
Background Tasks do not work for me since they are unreliable. However, I have the Audio, Airplay, and Picture in Picture Background mode activated (For purposes other than the Live Activity) and so when I run this code:
timer = Timer(timeInterval: 1, repeats: true, block: { [weak self] (timer) in
guard let self = self else { return }
self.value += 1
let state = TempAttributes.ContentState(timer: self.value)
Task { #MainActor in
await deliveryActivity.update(using: state)
}
})
RunLoop.main.add(timer!, forMode: .common)
It technically should work and when I add a break point in the timer, it gets called and the value gets updated but the Live Activity UI does not.
This works on 16.2 but unfortunately it does not work on 16.1! Any ideas why?

Cancel a smart alarm without any haptic feedback

I have create a smart alarm which relies on WKExtendedRuntimeSession.
There should be a possibility to manually stop the background session by, for example navigating back in the view hierarchy.
class BackgroundSessionController {
private var session: WKExtendedRuntimeSession?
func start() {
guard session?.state != .running else { return }
if nil == session || session?.state == .invalid {
session = WKExtendedRuntimeSession()
}
print("session started")
session?.start(at: Date())
}
func stopManual() {
session?.invalidate()
}
func stopByAlarm() {
session?.notifyUser(hapticType: .stop)
session?.invalidate()
}
}
When firing the function stopManual, and so invalidating the session I receive the message:
App has been running in the background but failed to play a scheduled
alarm. Would you like to disable the app's ability to run background
tasks ...
Seems that manually invalidating a session requires a haptic notification as well ?
How can I invalidate the session without the haptic feedback ?
added example:
let's say i'm a terrorist and i'm making a secret bomb which fires when movement stops. So you need to keep moving or else a timer starts counting down.
I Activate the app, I need to enable background modes, else the sensors stop working when the app goes into the background.
When movement stops, a smart alarm timer will fire .start(at:) which
counts down from 10 minutes.
I'm using smart alarm as functionality, which allows me to use 30 minutes of background modes. When these 30 minutes are finished and the person is still moving, i want to invalidate and then restart the session without sending any haptic feedback (the person will notice something isn'tright and deactivates the bomb)
What to use in this case then? This example is a bit weird but almost the same functionality I want.
The documentation of WKExtendedRuntimeSession clearly states this behaviour:
For sessions started with start(at:), you can only call invalidate() when the app is active. For all other sessions, you can call invalidate() to end a session at any time.
Since you are passing the current date for start(at:), why don't you just use start() instead and then you can call invalidate() even while your app is inactive. If you actually call start(at:) with a future date, then you don't have any alternatives.
The docs also state that you must play a haptic during your session. So if your session has started, you cannot invalidate it without playing a haptic. If your session hasn't started yet, you can invalidate it.
During the session, your app must trigger the alarm by calling the session’s notifyUser(hapticType:repeatHandler:) method.
If you fail to play a haptic during the session, the system displays a warning and offers to disable future sessions.
Bear in mind, this is probably a designed feature of watchOS. Due to the battery constraints of Apple Watches, watchOS puts an even bigger emphasis on apps being energy efficient, so if your app uses a background mode and the system thinks it might be abusing it (by declaring a smart alarm background mode, but not playing an alarm), it will alert the user.

Apple Watch: WKInterfaceDevice.current().play(.success) not working

I try to let the  Watch vibrate from within my code:
WKInterfaceDevice.current().play(.success)
but nothing happens. I also tried to ensure to be on the main thread:
DispatchQueue.main.async {
WKInterfaceDevice.current().play(.success)
}
still nothing. Am I missing something here? I expected it to be an easy task, but I fail completely...
Maybe your watch app is not in the active state? Citing the official documentation:
This method has no effect when called while your shared WKExtension object's applicationState property is either background or inactive. By default, you cannot play haptic feedback in the background. The only exception are apps with an active workout session.
So, unless you have a running HKWorkoutSession, if your app is in background you're not allowed to play haptic.
Alternatively, instead of HKWorkoutSession you could use WKExtendedRuntimeSession to support running the app in the background so sounds and haptics work. This needs to be done using either the Physical therapy or Smart alarm session type.

How to put Apple Watch into waterproof mode?

I've got a swimming workout set up.
let configuration = HKWorkoutConfiguration()
configuration.activityType = .swimming
configuration.locationType = .outdoor
do {
workoutSession = try HKWorkoutSession(configuration: configuration)
workoutSession!.delegate = self
healthStore.start(workoutSession!)
} catch let error as NSError {
// Perform proper error handling here...
fatalError("*** Unable to create the workout session: \(error.localizedDescription) ***")
}
But my client is saying that the watch doesn't go into waterproof mode unless he manually makes it.
For context, "waterproof lock" is a mode that the Watch Series 2 is supposed to enter into when starting a swimming workout. From an Apple Support article:
When you start a swimming workout, your Apple Watch automatically locks the screen with Water Lock to avoid accidental taps. When you're done, turn the Digital Crown to unlock the screen and clear any water from your Apple Watch. You hear sounds and may feel some water on your wrist.
This functionality does not appear to be working with my app.
I only have a Series 0 to test on, so I can't confirm what's happening with my code with regards to the waterproof lock.
Am I missing something to make the workout force the watch into waterproof mode?
Available since watchOS 4:
https://developer.apple.com/documentation/watchkit/wkextension/2868458-enablewaterlock
// Only an application which is in an active workout or location session and is foreground is allowed to enable water lock
#available(watchOS 4.0, *)
open func enableWaterLock()
Call WKExtension.shared().enableWaterLock() when starting your swim / water workout.
There is currently no "waterproof mode". My client was under the impression that there was.
The native Apple Exercise app has a button that locks the watch and ignores interaction until the digital crown is rotated. This is not currently reproducible in third party apps.
The solution I have found is to disable all buttons on the watch app. This way, buttons are not accidentally tapped while in the water. The user has to force touch the watch to re-enable the buttons.

Is it possible to reopen a suspended app after a time delay in Swift?

I am using the following code to suspend the app.
UIControl().sendAction(Selector("suspend"), to: UIApplication.sharedApplication(), forEvent: nil)
do {
print("suspended")
} catch _ {
print("unable")
}
I was wondering is it possible to reopen the app after a certain time delay. Following code works for performing an action after time delay. But I don't know how to reopen the app at that time interval
let seconds = 300.0
let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
print("time delay")
})
It's is not possible and apps with such kind of "functionality" will be rejected by Appstore ;)
https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/StartingStopping.html
Always Be Prepared to Stop
An iOS app never displays a Close or Quit option
When people switch away from your app, iOS multitasking transitions it to the background and replaces its UI with the UI of the new app. To prepare for this situation, your app should:
Save user data as soon as possible and as often as reasonable. Do
this because an app in the background can be told to exit or
terminate at any time.
Save the current state when stopping at the finest level of detail possible. In this way, people don’t lose their
context when they switch back to your app. For example, if your app
displays scrolling data, save the current scroll position. You can
learn more about efficient ways to preserve and restore your app’s
state in Preserving Your App’s Visual Appearance Across Launches.
Some apps may need to keep running in the background while users run another app in the foreground. For example, users might want to keep listening to the song that’s playing in one app while they’re using a different app to check their to-do list or play a game. Learn how to handle multitasking correctly and gracefully in Multitasking.
Never quit an iOS app programmatically. People tend to interpret this as a crash. If something prevents your app from functioning as intended, you need to tell users about the situation and explain what they can do about it.