我正在尝试使watchOS复杂性每隔几分钟自动更新。在ComplicationCOntroller.swift中,我在getCurrentTimelineEntry()函数中设置了复杂功能,并且该功能首次运行,但仅当我启动WatchOS应用程序时才更新该复杂功能中显示的值。我可以将并发症设置为在后台自动更新吗?即使是设定的时间间隔,例如“在3分钟内更新”。这是我的ExtensionDelegate:
import WatchKit
import WatchConnectivity
class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
let session = WCSession.default
let defaults = UserDefaults.standard
let server = CLKComplicationServer.sharedInstance()
override init() {
super.init()
WKInterfaceDevice.current().isBatteryMonitoringEnabled = true
session.delegate = self
session.activate()
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("Session started on \(WKInterfaceDevice.current().name)")
defaults.set("32", forKey: "PhoneBatteryLevel")
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
print("Received application context: \(applicationContext["PhoneBatteryLevel"]!)")
defaults.set(applicationContext["PhoneBatteryLevel"], forKey: "PhoneBatteryLevel")
for complication in server.activeComplications! {
server.reloadTimeline(for: complication)
print("Reloading complications...")
}
}
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
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.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.
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)
}
}
}
}
以及相关的ComplicationController代码:
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
switch complication.family {
case .modularSmall:
let template = CLKComplicationTemplateModularSmallSimpleText()
template.textProvider = CLKSimpleTextProvider(text: "\(defaults.integer(forKey: "PhoneBatteryLevel"))")
template.tintColor = UIColor.yellow
let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
handler(entry)
case .modularLarge:
let template = CLKComplicationTemplateModularLargeStandardBody()
template.headerTextProvider = CLKSimpleTextProvider(text: "Battery Levels")
template.headerTextProvider.tintColor = UIColor.green
template.body1TextProvider = CLKSimpleTextProvider(text: "iPhone: \(defaults.integer(forKey: "PhoneBatteryLevel"))%")
template.body2TextProvider = CLKSimpleTextProvider(text: "Watch: \(getWatchBatteryLevel())%")
let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
handler(entry)
default:
return
}
}