无法启动beginBackgroundTask swift 3

时间:2017-10-04 14:21:44

标签: ios swift background-task

抱歉我被困了,但我正在尝试开始后台任务(XCode8,swift 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
    })
}

应用程序从未显示过#34;任务已经开始"信息。我做错了什么?

2 个答案:

答案 0 :(得分:5)

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

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
}

另请注意,即使应用程序进入后台,您也应该使用beginBackgroundTask/endBackgroundTask围绕您希望在短时间内继续运行的任何类中的任何代码。

答案 1 :(得分:1)

到期处理程序块在后台一段时间后被调用(通常是5分钟左右)。 如果后台任务需要花费大量时间来完成,那么这用于编写清理逻辑。

您的代码没有任何问题,您只需要等待在后台以使后台任务过期。