我正在使用backgroundTaskIdentifier让秒表在应用程序关闭时继续。当应用程序关闭时,计数器会正常更新。
但我希望在应用程序关闭时收到弹出警报通知。现在,当我打开应用程序时它会弹出,但这对我没有帮助,因为计时器已经停止了。
相关问题。如果服务器没有推送任何内容,应用程序是否可以推送通知?我的意思是,当计时器完成时,我可以给我的应用程序添加标记吗?
变量声明
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
ViewDidLoad
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTimerBasedViews", name: Timer.notificationSecondTick, object: timer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "timerComplete", name: Timer.notificationComplete, object: timer)
backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
})
适用功能
func updateTimerBasedViews() {
updateTimerLabel()
updateProgressView()
}
func timerComplete() {
switchToPickerView()
playAlarm()
// TO DO : ADD UIAlert
let alert = UIAlertController(title: title, message: "Time to do it!", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
//self.presentViewController(alert, animated: true, completion: nil) // old
presentViewController(alert, animated: true) { () -> Void in
let localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Testing"
localNotification.alertBody = "Hello World!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
应用程序委托(delegate)
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
最佳答案
如果您不想在应用程序中显示弹出窗口,而是在设备后台任务中显示 UIAlertAction
,则不是正确的方法。它将在您的应用程序上下文中显示气泡,而不是操作系统系统。
您的方法应该是使用 local notifications
你应该意识到这样的事情:
application.registerUserNotificationSettings(UIUserNotificationSettings (forTypes: UIUserNotificationType.Alert, categories: nil))
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Testing"
localNotification.alertBody = "Hello World!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 5)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
你可以找到很多教程,比如this
关于swift - uibackgroundTaskIdentifier - 应用程序关闭时 UIAlert 不会弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33968522/