【发布时间】:2015-05-10 06:53:13
【问题描述】:
我需要一种方法来确定在完成矿石的“未知”时间之后的时间。
启动计时器后,它需要计算何时发送本地通知。 我需要一种方法,以便应用程序可以完全关闭并仍然通知他们。
谢谢
这是我在实现“notificationsAllowed”代码时遇到的错误。
【问题讨论】:
标签: swift nsdate uilocalnotification nscalendar
我需要一种方法来确定在完成矿石的“未知”时间之后的时间。
启动计时器后,它需要计算何时发送本地通知。 我需要一种方法,以便应用程序可以完全关闭并仍然通知他们。
谢谢
这是我在实现“notificationsAllowed”代码时遇到的错误。
【问题讨论】:
标签: swift nsdate uilocalnotification nscalendar
要计算结束时间,您可以使用
timerEndTime = NSDate(timeIntervalSinceNow:NSTimeInterval(oreWanted * 11))
所以你得到一个NSDate 对象。现在您可以在计算出的时间触发UILocalNotification:
注意:您需要在应用启动时请求通知权限。我在这里用notificationsAllowed 和soundsAllowed 简化了这一点,它们是我的AppDelegate 中的布尔变量。
let appDelegate = UIApplication.sharedApplication.delegate as! AppDelegate
if appDelegate.notificationsAllowed {
let notification = UILocalNotification()
notification.fireDate = timerEndTime
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.alertBody = "Notification body text"
notification.alertTitle = "Notification alert title"
if appDelegate.soundsAllowed {
notification.soundName = UILocalNotificationDefaultSoundName
}
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
编辑
在 AppDelegate 中为应用注册通知:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var notificationsAllowed = false
var notificationSoundAllowed = false
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationSettings = UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings)
return true
}
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types & UIUserNotificationType.Alert != nil {
self.notificationsAllowed = true
}
if notificationSettings.types & UIUserNotificationType.Sound != nil {
self.notificationSoundAllowed = true
}
}
【讨论】:
NSUserDefaults,并在用户下次激活应用时读取。因此无需让应用程序在后台运行。