Reputation: 137
Hello I hope someone can help me with this issue. I'm still new to ios development. I'm testing UILocalNotification, I'm able to set the firedate and everything is working fine but if the firedate is in the past the local notification fires right away. Also everytime I exit the app the notification will show up again in the notification center. Is there anyway to make sure that a local notification only fires if the date is set to the future? I searched SO but I couldn't find my answer. Any help will be greatly appreciated.
This is the code in the viewDidLoad method
class ViewController: UIViewController {
var time : NSDate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var comp = NSDateComponents()
comp.year = 2015
comp.month = 01
comp.day = 20
comp.hour = 16
comp.minute = 00
var calender = NSCalendar.currentCalendar()
time = calender.dateFromComponents(comp)
var notification = UILocalNotification()
notification.alertBody = "this works"
notification.fireDate = time
notification.timeZone = NSTimeZone.defaultTimeZone()
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
This is the code in the AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationType = UIUserNotificationType.Alert | UIUserNotificationType.Badge
let notificationSetiings = UIUserNotificationSettings(forTypes: notificationType, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(notificationSetiings)
return true
}
Upvotes: 3
Views: 1062
Reputation: 236558
The problem there is that you have to define local time zone before setting the fireDate.
Upvotes: 0
Reputation: 107231
If you set the fireDate to a past date, the notification will fire right away. Apple is designed and documented that well in their UILocalNotification documentation.
fireDate
PropertyThe date and time when the system should deliver the notification. Declaration
Swift
@NSCopying var fireDate: NSDate?
Objective-C
@property(nonatomic, copy) NSDate *fireDate
Discussion
The fire date is interpreted according to the value specified in the timeZone property. If the specified value is nil or is a date in the past, the notification is delivered immediately.
So it's programmers responsibility to handle this situation. One thing you can do is, compare the date you are going to set with current date. If it is less don't set it.
Upvotes: 5