1

我正在XCode 11.0 beta 5上开发一个独立的手表应用程序。一切正常,除了后台刷新。当我打开应用程序时,我正在使用以下代码来安排后台刷新任务:

let fireDate = Date(timeIntervalSinceNow: 60.0 * 30.0)
// optional, any SecureCoding compliant data can be passed here
let userInfo = ["reason" : "update UI"] as NSDictionary

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.")
      }
}

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>)永远不会被调用。如果我使用 XCode 中的Debug->Simulate background fetch 选项,则会调用该方法。

4

2 回答 2

1

尝试将其安排在 中applicationDidResignActive,而不是从控制器中。

只有当应用程序在后台时才会这样做。如果应用程序不在后台,它似乎认为不需要这样做。

您可以applicationDidResignActive通过按表冠按钮进行点火。

于 2020-08-01T19:29:24.157 回答
1

我有完全相同的问题,即使我不将应用程序作为独立运行。该问题仅发生在 watchOS 6 上。

有谁知道解决方案是什么?

这是我的源代码:

import WatchKit

class ExtensionDelegate: NSObject, WKExtensionDelegate {

func applicationDidFinishLaunching() {
    // Perform any final initialization of your application.
    print("applicationDidFinishLaunching")
    self.reloadActiveComplications()
    scheduleNextReload()
}

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.
    self.reloadActiveComplications()
    scheduleNextReload()
}

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.
    print("background")
    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.
            scheduleNextReload()
            self.reloadActiveComplications()
            backgroundTask.setTaskCompletedWithSnapshot(true)
        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(true)
        case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
            // Be sure to complete the URL session task once you’re done.
            urlSessionTask.setTaskCompletedWithSnapshot(true)
        default:
            // make sure to complete unhandled task types
            task.setTaskCompletedWithSnapshot(true)
        }
    }
}

func reloadActiveComplications() {
    let server = CLKComplicationServer.sharedInstance()

    print("ExtensionDelegate: requesting reload of complications")
    for complication in server.activeComplications ?? [] {
        server.reloadTimeline(for: complication)
    }
}

func scheduleNextReload() {
    var targetDate:Date
    let currentDate = Date()

    let timezoneOffset =  TimeZone.current.secondsFromGMT()
    let epochDate = currentDate.timeIntervalSince1970
    let timezoneEpochOffset = (epochDate + Double(timezoneOffset))
    let timeZoneOffsetDate = Date(timeIntervalSince1970: timezoneEpochOffset)

    targetDate = timeZoneOffsetDate.addingTimeInterval(120)
    print("ExtensionDelegate: scheduling next update at %@", "\(timeZoneOffsetDate)")
    print("ExtensionDelegate: scheduling next update at %@", "\(targetDate)")

    WKExtension.shared().scheduleBackgroundRefresh(
        withPreferredDate: targetDate,
        userInfo: nil,
        scheduledCompletion: { error in
            // contrary to what the docs say, this is called when the task is scheduled, i.e. immediately
            NSLog("ExtensionDelegate: background task %@",
                  error == nil ? "scheduled successfully" : "NOT scheduled: \(error!)")
        }
    )
}

}

于 2019-10-21T12:44:10.757 回答