执行代码,当应用程序在后台不工作在物理设备(SWIFT)

我正在制作一个应用程序,这是依赖于在后台执行一些小代码,我遇到了一个奇怪的问题。
该应用程序有一个计时器,一个NSTimer() 。 所有这一切背后的原理类似于计时器(在所有iOS设备上安装的时钟应用程序中),也就是说,当计时器结束时,会显示一个UILocalNotification

当我在Xcode的仿真设备上运行它时,一切都按预期工作,但是当我在iPhone上testing它时,没有任何通知。 这是沿着以下方面的东西:

 var end = timerHasEnded() if end == true{ println("the timer has ended") } 

并没有工作。 所以我检查了应用程序是否通过这样做来检测后台UIApplicationState ,而不是在物理设备上。 有趣的是,它在模拟设备上是这样做的。

我试图在后台线程上运行计时器,使用QOS_CLASS_BACKGROUNDdispatch_async无济于事。 有谁能够帮助我?

你可以安排一个UILocalNotification出现延迟后,当延迟是剩余时间留在你的报警?

 var date: NSDate = /*time until your timer expires*/ let app = UIApplication.sharedApplication() let oldNotifications = app.scheduledLocalNotifications if oldNotifications.count > 0 { app.cancelAllLocalNotifications() } let alarm = UILocalNotification() alarm.fireDate = date alarm.timeZone = NSTimeZone.defaultTimeZone() alarm.repeatInterval = 0 alarm.soundName = "myAlarmSound.caf" alarm.alertBody = "Do something!" app.scheduleLocalNotification(alarm) 

我从Apple提供的Obj-C示例编写了这段代码。

https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html