首页 文章

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

提问于
浏览
0

我正在制作一个应用程序,它依赖于在后台执行一些次要代码,我遇到了一个特殊的问题 .
该应用程序有一个计时器, NSTimer() . 所有这些背后的原理类似于计时器(在时钟应用程序中,安装在所有iOS设备上),这意味着,当计时器结束时,显示 UILocalNotification .

当我在Xcode中的模拟设备上运行时,一切都按预期工作,但是当我在iPhone上测试它时,没有通知 . 它有以下几点:

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

它没有用 . 所以我检查了应用程序是否通过执行此操作检测到背景 UIApplicationState 并且它不在物理设备上 . 有趣的是,它在仿真设备上实现了这一点 .

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

1 回答

  • 1

    您是否可以安排在延迟后显示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

相关问题