背景
我创建了一个示例计时器应用程序,它从特定值计数到零。标签显示还剩多少时间。
每次 NSTimer
(1 秒间隔)调用 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)
问题
我可以更改任何内容来解决此问题吗?
提前致谢:)
最佳答案
默认情况下,NSTimer
不会在实际设备的后台运行。它仅适用于模拟器。但是,您可以使用 UIApplication
的方法 beginBackgroundTaskWithExpirationHandler
执行后台任务,但是 Apple 为后台执行设置了硬性限制(如果我没记错的话,只有 180 秒)。
建议使用 UILocalNotification
而不是后台任务。
关于ios - 后台任务仅适用于模拟器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630687/