首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >backgroundTaskIdentifier - UIAlert在应用程序关闭时不会弹出

backgroundTaskIdentifier - UIAlert在应用程序关闭时不会弹出
EN

Stack Overflow用户
提问于 2015-11-28 06:40:59
回答 1查看 100关注 0票数 0

当应用程序关闭时,我使用backgroundTaskIdentifier让秒表继续运行。当应用程序关闭时,计数器会很好地更新。

但是,当应用程序关闭时,我想收到弹出警报通知。现在,当我打开应用程序时,它会弹出,但这对我没有帮助,因为计时器已经停止了。

相关问题。如果没有从服务器上推送任何信息,应用程序可以有推送通知吗?我的意思是,当计时器完成时,我能给我的应用程序打上徽章吗?

变量声明

代码语言:javascript
复制
var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

ViewDidLoad

代码语言:javascript
复制
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!)
    })

适用职能

代码语言:javascript
复制
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)
    }

AppDelegate

代码语言:javascript
复制
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Sound, .Alert, .Badge], categories: nil))
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-28 07:24:53

如果您想显示弹出,而不是在您的应用程序中,而是在您的设备后台,使用显示UIAlertAction的任务是不正确的。它将在应用程序上下文中显示气泡,而不是os系统。

您的方法应该是使用本地通知

你应该意识到这样的感觉:

代码语言:javascript
复制
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)

您可以找到很多教程,比如

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33968522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档