ios - 后台任务仅适用于模拟器

标签 ios swift timer background-process uilocalnotification

背景

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

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

代码

AppDelegateapplicationDidEnterBackground()中,我有以下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/

相关文章:

iphone - 使用 sizeWithFont 时的高度 :constrainedToSize:lineBreakMode with NSLineBreakByTruncatingTail

javascript - Vapor 3 接收包含 BOOL 的字符串化 JSON

c++ - 如何使用事件循环管理线程?

ios - iOS CoreData fetchRequest具有顺序列变音符号敏感

ios - 使用 GTMOAuth2 在登录时检索 gmail 地址

ios - bodyWithEdgeLoopF​​romRect 不能横向工作

ios - 在表格 View 中拉动刷新后滚动到屏幕顶部

ios - 当整个屏幕设置为 RTL 时,我们如何将 tableview 单元格的语义更改为 LTR?

java - 将时钟格式的字符串解析为int

ios - 如何快速计算接收变量之间的时间