Background
I have created a sample timer app that counts from a specific value down to zero. A label displays how much time is left.
Every time the NSTimer
(1s interval) calls countDownSecs()
it prints how many seconds are left and executes println("countDownSecs()")
. When the countdown has reached 0
seconds it sends a local push notification.
When running in the simulator that works and even for like 5 minutes it stays in the background and continuously prints the seconds left and countDownSecs()
.
On the other hand, when running on an actual device (iPhone 4S, iOS 8.1.3 and iOS 8.3) it stops immediately when entering the background. (It worked before on the one w/ iOS 8.3. I thought it might be because the iPhone 4S can not handle that but the iPhone 4S simulator works perfectly fine.)
Code
In the AppDelegate
's applicationDidEnterBackground()
I have the following code for the UILocalNotification
:
var alarmTime: NSDate = NSDate()
var app: UIApplication = UIApplication.sharedApplication()
var notifyAlarm: UILocalNotification = UILocalNotification()
//counterAll contains the total amount of seconds
alarmTime.dateByAddingTimeInterval(NSDate.timeIntervalSinceReferenceDate())
notifyAlarm.fireDate = NSDate(timeIntervalSinceNow: counterAll)
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
notifyAlarm.repeatInterval = NSCalendarUnit(0)
notifyAlarm.soundName = "Time's Up.m4a"
notifyAlarm.alertBody = "Time's Up! - Your timer has ended."
app.scheduleLocalNotification(notifyAlarm)
Question
Can I change anything to fix this issue?
Thanks in advance :)
By default,
NSTimer
won't work in the background in actual devices. It works in simulators only. However, you can execute background tasks withUIApplication
s methodbeginBackgroundTaskWithExpirationHandler
, however Apple has set a hard limit for background execution (180 seconds only if I remember correctly).It is advisable to use
UILocalNotification
s instead of background tasks.