无法启动 beginBackgroundTask swift 3

2023-11-27

抱歉,我被卡住了,但我正在尝试启动后台任务(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
    })
}

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


您对后台任务的使用是错误的。

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

所以你应该做类似的事情:

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即使应用程序进入后台,您也希望在短时间内继续运行任何类中的任何代码。

在此设置中,如果任务在while循环仍在工作然后expirationHandler被并行调用不同的线程。您应该使用处理程序来停止您的代码并允许它到达application.endBackgroundTask(bgTask) line.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法启动 beginBackgroundTask swift 3 的相关文章

随机推荐