无法启动beginBackgroundTask swift 3

Ale*_*lex 5 ios swift background-task

抱歉,我被卡住了,但是我正在尝试启动后台任务(XCode8,迅速3)

来自此处的示例: https : //developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html#//apple_ref/doc/uid/TP40007072-CH4-SW3

在AppDelegate.swift中:

func applicationDidEnterBackground(_ application: UIApplication) {
    var bgTask: UIBackgroundTaskIdentifier = 0;
    bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
        print("The task has started")
        application.endBackgroundTask(bgTask)
        bgTask = UIBackgroundTaskInvalid
    })
}
Run Code Online (Sandbox Code Playgroud)

该应用程序从未显示“任务已开始”消息。我究竟做错了什么?

rma*_*ddy 6

您使用后台任务是完全错误的。应该是这样的:

func applicationDidEnterBackground(_ application: UIApplication) {
    var finished = false
    var bgTask: UIBackgroundTaskIdentifier = 0;
    bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
        // Time is up.
        if bgTask != UIBackgroundTaskInvalid {
            // Do something to stop our background task or the app will be killed
            finished = true
        }
    })

    // Perform your background task here
    print("The task has started")
    while !finished {
        print("Not finished")
        // when done, set finished to true
        // If that doesn't happen in time, the expiration handler will do it for us
    }

    // Indicate that it is complete
    application.endBackgroundTask(bgTask)
    bgTask = UIBackgroundTaskInvalid
}
Run Code Online (Sandbox Code Playgroud)

还要注意,beginBackgroundTask/endBackgroundTask即使应用程序进入后台,您也应该在任何想要长时间运行的类中使用任何代码。


Pun*_*rma 4

过期处理程序块会在后台运行一段时间(通常是 5 分钟左右)后被调用。如果您的后台任务需要花费大量时间才能完成,这意味着用于编写清理逻辑。

你的代码没有问题,你只需要在后台等待后台任务过期即可。

  • @PuneetSharma 等待过期处理程序被调用来调用“endBackgroundTask”是一种糟糕的做法,会让您的应用程序浪费比其需要更多的资源。当你的后台任务完成时,你应该立即告诉 iOS。 (2认同)