I'm using backgroundTaskIdentifier to get the stopwatch to continue when the app is closed. The counter updates fine when the app is closed.
But I would like to receive my popup alert notification when the app is closed. Right now it pops up when I open the app but that doesnt help me because the timer has already stopped.
Related question. Can an app have push notifications if nothing is being pushed from a server? I mean can I badge my app when the timer is complete?
Variable declaration
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
ViewDidLoad
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTimerBasedViews", name: Timer.notificationSecondTick, object: timer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "timerComplete", name: Timer.notificationComplete, object: timer)
backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
})
Applicable functions
func updateTimerBasedViews() {
updateTimerLabel()
updateProgressView()
}
func timerComplete() {
switchToPickerView()
playAlarm()
// TO DO : ADD UIAlert
let alert = UIAlertController(title: title, message: "Time to do it!", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
//self.presentViewController(alert, animated: true, completion: nil) // old
presentViewController(alert, animated: true) { () -> Void in
let localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Testing"
localNotification.alertBody = "Hello World!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
AppDelegate
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))