问题
I need my application to store some local notifications
that should be launched on a specific time.
My application is simple. The user can book times using a UIDatePicker
. The notification is to be fired 2 minutes before that booked time.
For now i am trying to manually insert a time that the notification should be fired at. I am using this code:
let notification = UILocalNotification()
self.timePicked = " 22:38:00 +0000"
timeForLocalPush = defaults.objectForKey("timeForLocalPush") as! String
timeForLocalPush = timeForLocalPush + self.timePicked
print(timeForLocalPush) // this prints for this example today, 2016-08-30 22:38:00 +0000
dateFormatter.dateFormat = "YYY-MM-dd"
notification.fireDate = dateFormatter.dateFromString(timeForLocalPush)
notification.timeZone = NSCalendar.currentCalendar().timeZone
notification.alertBody = self.nameField.text! + " Har bokat tid nu!"
UIApplication.sharedApplication().scheduleLocalNotification(notification)
What happens is that the notification is fired instantly after booking the time. Desired action is this:
Current Time: 14:17
Client books for this time: 15:00
Local notification is set to be fired: 14:58
If you need any additional information just tell me. Thank you
回答1:
initially check your date format it is in wrong dateFormatter.dateFormat = "YYY-MM-dd"
, it is in dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
for e.g
let localNotification1 = UILocalNotification()
localNotification1.alertBody = "Your alert message "
localNotification1.timeZone = NSCalendar.currentCalendar().timeZone
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
localNotification1.fireDate = formatter.dateFromString("2016-08-30 22:38:00")
UIApplication.sharedApplication().scheduleLocalNotification(localNotification1)
回答2:
Please set your date format proper:
// this prints for this example today, 2016-08-30 22:38:00 +0000
//Your date format decalre: dateFormatter.dateFormat = "YYY-MM-dd"
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
来源:https://stackoverflow.com/questions/39227325/creating-a-local-notification-to-fire-at-a-specific-time