Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift watchos 6独立应用程序中未触发后台刷新任务_Swift_Background Task_Watchos_Watchos 6 - Fatal编程技术网

Swift watchos 6独立应用程序中未触发后台刷新任务

Swift watchos 6独立应用程序中未触发后台刷新任务,swift,background-task,watchos,watchos-6,Swift,Background Task,Watchos,Watchos 6,我正在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

我正在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句柄(\backgroundTasks:Set)

如果我使用XCode中的调试->模拟背景获取选项,就会调用该方法。

即使我没有独立运行该应用程序,我也会遇到完全相同的问题。这个问题只发生在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!)")
        }
    )
}
导入WatchKit
类extensionelegate:NSObject,wkextensionelegate{
func applicationdFinishLaunching(){
//执行应用程序的任何最终初始化。
打印(“ApplicationdFinishLaunching”)
self.reloadActiveComplements()
scheduleNextReload()
}
func applicationIDbecomeactive(){
//重新启动应用程序处于非活动状态时暂停(或尚未启动)的所有任务。如果应用程序以前位于后台,可以选择刷新用户界面。
self.reloadActiveComplements()
scheduleNextReload()
}
func applicationWillResignActive(){
//当应用程序即将从活动状态移动到非活动状态时发送。这可能发生在某些类型的临时中断(如来电或短信)或用户退出应用程序并开始转换到后台状态时。
//使用此方法暂停正在进行的任务、禁用计时器等。
}
func句柄(uuBackgroundTasks:Set){
//当系统需要在后台启动应用程序来处理任务时发送。任务以集合的形式到达,因此循环并处理每个任务。
打印(“背景”)
用于背景任务中的任务{
//使用switch语句检查任务类型
切换任务{
案例let backgroundTask作为WKApplicationRefreshBackgroundTask:
//完成后,确保完成后台任务。
scheduleNextReload()
self.reloadActiveComplements()
backgroundTask.setTaskCompletedWithSnapshot(true)
案例让snapshotTask作为WKSnapshotRefreshBackgroundTask:
//快照任务具有唯一的完成调用,请确保设置过期日期
snapshotTask.setTaskCompleted(restoredDefaultState:true,estimatedSnapshotExpiration:Date.distantFuture,userInfo:nil)
案例let connectivityTask as wkWatch connectivityRefreshBackgroundTask:
//完成后,请确保完成连接任务。
ConnectionTask.setTaskCompletedWithSnapshot(true)
案例让urlSessionTask作为WKURLSessionRefreshBackgroundTask:
//完成后,请确保完成URL会话任务。
urlSessionTask.setTaskCompletedWithSnapshot(true)
违约:
//确保完成未处理的任务类型
task.setTaskCompletedWithSnapshot(true)
}
}
}
func重载{
让server=CLKComplicationServer.sharedInstance()
打印(“ExtensionLegate:请求重新加载文件”)
对于服务器中的复杂性。ActiveComplements???[]{
server.reloadTimeline(用于:复杂度)
}
}
func scheduleNextReload(){
var targetDate:日期
让currentDate=Date()
让timezoneOffset=TimeZone.current.secondsFromGMT()
设epochDate=currentDate.TimeIntervalence1970
让timezoneEpochOffset=(epochDate+Double(timezoneOffset))
让timeZoneOffsetDate=日期(timeIntervalSince1970:TimeZoneAppochOffset)
targetDate=timeZoneOffsetDate.addingTimeInterval(120)
打印(“ExtensionLegate:计划在%@”进行下一次更新,“\(timeZoneOffsetDate)”)
打印(“ExtensionLegate:计划在%@”和“\(targetDate)”进行下一次更新)
WKExtension.shared().scheduleBackgroundRefresh(
withPreferredDate:targetDate,
userInfo:nil,
scheduledCompletion:{中出现错误
//与文档中所说的相反,这是在计划任务时调用的,即立即调用
NSLog(“ExtensionLegate:后台任务%@”,
错误==nil?“计划成功”:“未计划:\(错误!)”)
}
)
}

}

尝试在
应用程序IDResignative
中调度,而不是从控制器调度

它仅在应用程序位于后台时才执行此操作。如果应用程序不在后台,它似乎不认为需要这样做


您可以通过按下crown按钮使
ApplicationIDResignative
启动。

这是我唯一的设备调试问题,请在模拟器上尝试。在模拟器上它对我有效。我看到了同样的问题。看来从watchOS6 WKRefreshBackgroundTask无法正常工作。你们中的任何一位有幸让WKRefreshBackgroundTask在watchOS6中工作吗?我现在也遇到了这个问题。从Xcode 11.3和WatchOS 6.1.1开始,WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate:Date(timeIntervalSinceNow:interval),userInfo:userInfo)在Watchkit扩展委托中运行时没有错误(在完成启动时)。但handle(uu backgroundTasks:Set)永远不会在模拟器上调用!有什么消息吗?