Using the sample code from WWDC as a base, I'm trying to get my WatchOS 3 extension to update in the background after sending application context from the iPhone. Here is the code on the watch extension.
WatchOS code:
Here I schedule a background task when the user taps a button in the view. I then use the crown to go into background. I then atempt to send the information from the iPhone app. The Watch App does enter the func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) function but it never finds a WatchConnectivityRefreshBackgroundTask to process. (just skips to the "else" case in my code below)
@IBAction func ScheduleRefreshButtonTapped() {
/
let fireDate = Date(timeIntervalSinceNow: 20.0)
/
let userInfo = ["reason" : "background update"]
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo) { (error) in
if (error == nil) {
print("successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire.")
}
}
}
override func awake(withContext context: AnyObject?) {
super.awake(withContext: context)
WKExtension.shared().delegate = self
if (WCSession.isSupported()) {
let session = WCSession.default()
session.delegate = self
session.activate()
print("Session Activated")
}
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>)
for task : WKRefreshBackgroundTask in backgroundTasks {
print("received background task: ", task)
if (WKExtension.shared().applicationState == .background) {
timeDisplayLabel.setText("state= background")
if task is WKWatchConnectivityRefreshBackgroundTask {
print ("Got The Info")
}
else {
print ("processing:", task)
}
}
else if let urlTask = task as? WKURLSessionRefreshBackgroundTask {
let backgroundConfigObject = URLSessionConfiguration.background(withIdentifier: urlTask.sessionIdentifier)
let backgroundSession = URLSession(configuration: backgroundConfigObject, delegate: self, delegateQueue: nil)
print("Rejoining session ", backgroundSession)
}
/
task.setTaskCompleted()
}
}
}
iPhone Code
WCSession *session=[WCSession defaultSession];
NSLog(@"ACTIVATION STATE: %ld",session.activationState);
NSUInteger transfers = [WCSession defaultSession].remainingComplicationUserInfoTransfers;
NSArray *keys = [NSArray arrayWithObjects:@"TODAY_EARNINGS", @"YESTERDAY_EARNINGS", nil];
NSArray *objects = [NSArray arrayWithObjects:[NSString stringWithFormat:@"$%@", [[response.rows objectAtIndex:1] objectAtIndex:1]], [NSString stringWithFormat:@"$%@", [[response.rows objectAtIndex:0] objectAtIndex:1]], nil];
_userInfo = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
[session updateApplicationContext:_userInfo error:nil];
NSLog(@"Sending background request to Apple Watch");