Trying to implement beginBackgroundTaskWithExpirationHandler and UILocalNotification

百般思念 提交于 2019-12-03 17:38:54

问题


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()
}

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?


回答1:


In the code sample, the timer you create will only fire once as you have set the "repeats" value to false in the initialiser.



来源:https://stackoverflow.com/questions/28313702/trying-to-implement-beginbackgroundtaskwithexpirationhandler-and-uilocalnotifica

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!