swift - 在 iOS8 上以后台模式运行周期性任务

标签 swift background ios8

当我的应用程序在 iOS8 上处于后台模式时,我想运行一个周期性任务。我快速编写了以下代码但失败了。有人能指出哪里出了问题吗?

这是我来自 AppDelegate.swift 的代码

let backgroundQueue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND,0)

func applicationDidEnterBackground(application: UIApplication) {
    println("did enter background")
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

func myBackgroundTask() {
    NSThread.sleepForTimeInterval(0.5)
    println("this is back ground task")
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

最佳答案

有人告诉我调用“beginBackgroundTaskWithName”就是答案。

func applicationDidEnterBackground(application: UIApplication) {
    println("did enter background")
    application.beginBackgroundTaskWithName("myBgTask", expirationHandler: nil)
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

func myBackgroundTask() {
    NSThread.sleepForTimeInterval(0.5)
    println("this is back ground task")
    dispatch_async(self.backgroundQueue, myBackgroundTask)
}

关于swift - 在 iOS8 上以后台模式运行周期性任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27338027/

相关文章:

css - 背景颜色不覆盖页面

ios - 快速自动更改背景图像

swift - 查找 Swift String 中所有 Substring 实例的有效方法

swift - Swift 中的条件 if 语句

ios - UIScreenEdgePanGestureRecognizer 在自定义键盘扩展中不起作用

ios - Swift Keyboard Extension更新NSUserDefaults

ios - iOS8 中 iOS 模拟器和设备之间 NSNumber 到 BOOL 的不同结果

swift - 每 30 分钟更新一次徽章编号

iphone - 在 UITableViewController 代码中的 UITableView 后面添加 UIView

ios - BLE后台扫描iOS