本地通知立即触发,而不是按计划触发
Local notifications firing immediately instead of when they are scheduled
我一直在尝试按工作日安排本地通知,但它们似乎会立即触发,而不是在我安排它们时触发。这是我在 didFinishLaunchingWithOption
s:
中 AppDelegate 中的代码
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
var notification = UILocalNotification()
var components = NSDateComponents()
var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
components.weekday = 5
components.hour = 9
components.minute = 24
notification.alertBody = "Notification test"
notification.fireDate = calendar?.dateFromComponents(components)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
关于为什么它可能不起作用的任何线索?
尝试设置一个year/month因为它是从01/01/1970创建的,所以日期是过去的=>立即触发
正如其他人提到的,确保指定 components
对象的 year
和 month
属性。
components.year = 2016
components.month = 6
您的代码的部分当前触发日期如下:
0001-01-01
这意味着通知将在“1”年的一月份触发,而不是在 2016 年。
您需要使用notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
我一直在尝试按工作日安排本地通知,但它们似乎会立即触发,而不是在我安排它们时触发。这是我在 didFinishLaunchingWithOption
s:
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
var notification = UILocalNotification()
var components = NSDateComponents()
var calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
components.weekday = 5
components.hour = 9
components.minute = 24
notification.alertBody = "Notification test"
notification.fireDate = calendar?.dateFromComponents(components)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
关于为什么它可能不起作用的任何线索?
尝试设置一个year/month因为它是从01/01/1970创建的,所以日期是过去的=>立即触发
正如其他人提到的,确保指定 components
对象的 year
和 month
属性。
components.year = 2016
components.month = 6
您的代码的部分当前触发日期如下:
0001-01-01
这意味着通知将在“1”年的一月份触发,而不是在 2016 年。
您需要使用notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];