Background Task works on Simulator only

﹥>﹥吖頭↗ 提交于 2019-12-25 05:29:07

问题


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 :)


回答1:


By default, NSTimer won't work in the background in actual devices. It works in simulators only. However, you can execute background tasks with UIApplications method beginBackgroundTaskWithExpirationHandler, however Apple has set a hard limit for background execution (180 seconds only if I remember correctly).

It is advisable to use UILocalNotifications instead of background tasks.



来源:https://stackoverflow.com/questions/30630687/background-task-works-on-simulator-only

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