I'm developing an independent watch app and I have a background task every 60 minutes. But don't have anything happen when I close app or run background mode in over 24 hours.
I have use below code: ViewController.swift
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
setScheduleBackgroundJob {
// Set success
}
}
func setScheduleBackgroundJob(completed: @escaping () -> Void) {
let dateStartBackgroundTask = Date(timeInterval: TASK_INTERVAL_TIME.timeInterval, since: Date())
WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: dateStartBackgroundTask, userInfo: nil) { error in
if let error = error {
// log if have error
print("Error: ", error.localizedDescription)
return
}
print("BACKGROUND TASK: ", Date());
completed()
}
}
@IBAction func closeApp() {
setScheduleBackgroundJob {
exit(0)
}
}
ExtensionDelegate.swift
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.
createBackgroundSceduleTask()
LocalStorageManager.logCollectData(content: "Collect Health Data Background \(Date())")
DataManager.shared.collectData(bgTask: backgroundTask)
// backgroundTask.setTaskCompletedWithSnapshot(false)
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.
connectivityTask.setTaskCompletedWithSnapshot(false)
case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// Be sure to complete the URL session task once you’re done.
DataManager.shared.handleData(urlSessionTask)
// urlSessionTask.setTaskCompletedWithSnapshot(false)
case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask:
// Be sure to complete the relevant-shortcut task once you're done.
relevantShortcutTask.setTaskCompletedWithSnapshot(false)
case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask:
// Be sure to complete the intent-did-run task once you're done.
intentDidRunTask.setTaskCompletedWithSnapshot(false)
default:
// make sure to complete unhandled task types
task.setTaskCompletedWithSnapshot(false)
}
}
}