gpt4 book ai didi

ios - 当应用程序处于后台且不在物理设备上运行时执行代码 (SWIFT)

转载 作者:行者123 更新时间:2023-11-29 01:51:57 25 4
gpt4 key购买 nike

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

当我在 Xcode 的模拟设备上运行它时,一切都按预期工作,但是当我在我的 iPhone 上测试它时,没有任何通知。它是这样的:

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

关于ios - 当应用程序处于后台且不在物理设备上运行时执行代码 (SWIFT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com