[英]Executing code, when the application is in background not working on physical device (SWIFT)
I am making an app, that is reliant on executing some minor code in the background and I ran into a peculiar problem. 我正在制作一个应用程序,它依赖于在后台执行一些次要代码,但遇到了一个特殊的问题。
The app has a timer, an NSTimer()
. 该应用程序有一个计时器
NSTimer()
。 The principle behind all of this is similiar to that of timer (in Clock application, that is installed on all iOS devices), meaning, when the timer ends a UILocalNotification
is displayed. 所有这些背后的原理与计时器(在所有iOS设备上安装的Clock应用程序中)相似,也就是说,当计时器结束时会显示
UILocalNotification
。
Everything works as expected when I run it on an emulated device in Xcode, but when I test it on my iPhone, there are no notifications. 当我在Xcode的模拟设备上运行它时,一切都按预期运行,但是在iPhone上测试时,没有任何通知。 It is something along the lines of:
它遵循以下原则:
var end = timerHasEnded()
if end == true{
println("the timer has ended")
}
and it was not working. 而且它没有用。 So I checked if the application even detects the background
UIApplicationState
by doing this and it does not on the physical device. 因此,我检查了应用程序是否通过执行此操作甚至检测到后台
UIApplicationState
,并且它不在物理设备上。 Interestingly enough, it does so on an emulated device. 有趣的是,它是在模拟设备上执行的。
I tried running the timer on background thread, using QOS_CLASS_BACKGROUND
and dispatch_async
to no avail. 我尝试在后台线程上运行计时器,使用
QOS_CLASS_BACKGROUND
和dispatch_async
无济于事。 Can anybody help me? 有谁能够帮助我?
Could you just schedule a UILocalNotification to appear after a delay, when the delay was the remaining time left in your alarm? 当延迟是警报中剩余的时间时,您是否可以安排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)
I wrote this code from an Obj-C example provided by Apple. 我是从Apple提供的Obj-C示例中编写此代码的。
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.