swift - uibackgroundTaskIdentifier - 应用程序关闭时 UIAlert 不会弹出

标签 swift

我正在使用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/

相关文章:

ios - Int 不能转换为 UInt8?

SwiftUI - 将数据传递到不同的 View

swift - GeoFire + Swift+ Firebase : Save current location

ios - 在 Swift 中使用动画将按钮从一个 UITableViewCell 移动到另一个

ios - "The folder ' 文档 ' doesn' t 存在“Swift 中的错误

ios - 捕获两个图像并将其显示到两个 UIImageView

ios - 使用 NativeExpress admob 的 didSelectRowAtIndexPath 中的错误索引

ios - 如何在SwiftUI中允许在“文本”标签上选择文本?

ios - 如何为已添加到 UIViewController 之上的 tableView 添加自定义单元格?

iOS 11系统灰色