尝试实现beginBackgroundTaskWithExpirationHandler和UILocalNotification [英] Trying to implement beginBackgroundTaskWithExpirationHandler and UILocalNotification
问题描述
当我的应用程序进入后台时,我的AppDelegate
中包含以下代码:
I have the following code in my AppDelegate
for when my application enters the background:
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()
,但是它只执行一次.
I'm hoping that it executes a UILocalNotification()
every X number of seconds specified in the NSTimer.scheduledTimerWithTimeInterval()
however it only executes once.
我仍在努力弄清后台任务的工作方式.有什么我想念的吗?
I'm still trying to get my head around how background tasks work. Is there something I'm missing?
推荐答案
在代码示例中,您创建的计时器仅会触发一次,因为您已在初始化程序中将"repeats"值设置为false.
In the code sample, the timer you create will only fire once as you have set the "repeats" value to false in the initialiser.
这篇关于尝试实现beginBackgroundTaskWithExpirationHandler和UILocalNotification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!