后台任务仅适用于模拟器

时间:2015-06-03 21:04:13

标签: ios swift timer background-process uilocalnotification

背景

我创建了一个示例计时器应用程序,它从特定值减少到零。标签显示剩余时间。

每次NSTimer(1s间隔)调用countDownSecs()时,它会打印剩余的秒数并执行println("countDownSecs()")。当倒计时达到0秒时,它会发送本地推送通知。
模拟器中运行工作,甚至在5分钟内运行时,它会保留在后台并连续打印剩余的秒数countDownSecs()
另一方面,当在实际设备(iPhone 4S,iOS 8.1.3和iOS 8.3)上运行时,它会在进入后台时立即停止。 (之前它在iOS 8.3上使用过。我认为可能是因为iPhone 4S无法处理,但iPhone 4S模拟器工作得很好。)

代码

AppDelegate' applicationDidEnterBackground()我有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)

问题

我可以更改任何内容来解决此问题吗?

提前致谢:)

1 个答案:

答案 0 :(得分:0)

默认情况下,实际设备的后台中NSTimer 无法正常工作。它仅适用于模拟器。但是,您可以使用UIApplication方法beginBackgroundTaskWithExpirationHandler执行后台任务,但Apple已为后台执行设置了硬限制(仅在我没记错的情况下为180秒)。

建议使用UILocalNotification代替后台任务。