【问题标题】:Trying to implement beginBackgroundTaskWithExpirationHandler and UILocalNotification尝试实现 beginBackgroundTaskWithExpirationHandler 和 UILocalNotification
【发布时间】:2015-02-04 04:47:57
【问题描述】:

当我的应用程序进入后台时,我的AppDelegate 中有以下代码:

var backgroundUpdateTask: UIBackgroundTaskIdentifier!

func beginBackgroundUpdateTask() {
    self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
        self.endBackgroundUpdateTask()
    })
}

func endBackgroundUpdateTask() {
    UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
}

func doBackgroundTask() {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
        self.beginBackgroundUpdateTask()

        // Do something with the result.
        var timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "displayAlert", userInfo: nil, repeats: false)
        NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
        NSRunLoop.currentRunLoop().run()

        // End the background task.
        self.endBackgroundUpdateTask()
    })
}

func displayAlert() {
    let note = UILocalNotification()
    note.alertBody = "As a test I'm hoping this will run in the background every X number of seconds..."
    note.soundName = UILocalNotificationDefaultSoundName
    UIApplication.sharedApplication().scheduleLocalNotification(note)
}

func applicationDidEnterBackground(application: UIApplication) {
    self.doBackgroundTask()
}

我希望它每在NSTimer.scheduledTimerWithTimeInterval() 中指定的 X 秒数执行一次UILocalNotification(),但它只执行一次。

我仍在努力了解后台任务的工作原理。我有什么遗漏吗?

【问题讨论】:

  • 我的代码中缺少 var backgroundUpdateTask: UIBackgroundTaskIdentifier!。感谢您的提问,我找到了最后一块拼图。

标签: swift uilocalnotification uibackgroundtask


【解决方案1】:

在代码示例中,您创建的计时器只会触发一次,因为您在初始化程序中将“repeats”值设置为 false。

【讨论】:

    猜你喜欢
    • 2011-01-14
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多