[英]Background Task works on Simulator only
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()")
. 每次
NSTimer
(间隔为1s)调用countDownSecs()
它都会打印剩余的秒数并执行println("countDownSecs()")
。 When the countdown has reached 0
seconds it sends a local push notification. 当倒计时达到
0
秒时,它将发送本地推送通知。
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()
. 在可正常运行的模拟器中运行甚至大约5分钟后,它将停留在后台并连续打印剩余的秒数和
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. 另一方面,在实际设备(iPhone 4S,iOS 8.1.3和iOS 8.3)上运行时,进入背景时它会立即停止。 (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.)
(它以前在带iOS 8.3的系统上运行。我认为可能是因为iPhone 4S无法处理该问题,但iPhone 4S模拟器运行得很好。)
In the AppDelegate
's applicationDidEnterBackground()
I have the following code for the UILocalNotification
: 在
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)
Can I change anything to fix this issue? 我可以更改任何内容来解决此问题吗?
Thanks in advance :) 提前致谢 :)
By default, NSTimer
won't work in the background in actual devices. 默认情况下,
NSTimer
在实际设备中不会在后台运行。 It works in simulators only . 它仅适用于模拟器 。 However, you can execute background tasks with
UIApplication
s method beginBackgroundTaskWithExpirationHandler
, however Apple has set a hard limit for background execution (180 seconds only if I remember correctly). 但是,您可以使用
UIApplication
的方法beginBackgroundTaskWithExpirationHandler
来执行后台任务,但是Apple为后台执行设置了硬限制(只有在我没有记错的情况下,才需要180秒)。
It is advisable to use UILocalNotification
s instead of background tasks. 建议使用
UILocalNotification
代替后台任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.