2

I try to repeat a local notification every Monday. I found localNotification.repeatInterval = kCFCalendarUnitWeekOfYear; but I am not sure if it works. How can I show all local notification times in the future?

[[UIApplication sharedApplication] cancelAllLocalNotifications];

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setLocale:[NSLocale currentLocale]];

NSDateComponents *nowComponents = [gregorian components:NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:today];

[nowComponents setHour:18];
[nowComponents setMinute:05];
[nowComponents setSecond:00];
[nowComponents setWeekday:2];

NSDate * notificationDate = [gregorian dateFromComponents:nowComponents];

UILocalNotification* localNotification = [[UILocalNotification alloc] init];
//localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
localNotification.fireDate = notificationDate;
localNotification.repeatInterval = kCFCalendarUnitWeekOfYear;
localNotification.soundName = @"localNotification_Sound.mp3";
localNotification.alertBody = @"Message?";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
hantoren
  • 357
  • 2
  • 17
  • 1
    I see the commented out `fireData` line in your code up there. Why not try setting up a local notification to fire every 30 minutes and see if that works to start with? – Michael Dautermann Nov 14 '15 at 08:54
  • Actually a good idea. I will try it. Thanks – hantoren Nov 14 '15 at 08:56
  • I found out, that localNotification.repeatInterval = NSCalendarUnitMinute; will repeat the code every minute. But I wanna have a notification every Monday, so do I have to change something in my code? I am not sure if I have to use localNotification.repeatInterval = NSCalendarUnitWeekOfYear / NSCalendarUnitWeekday or kCFCalendarUnitWeekOfYear... – hantoren Nov 14 '15 at 10:46

1 Answers1

3

I tried out your code in my own simulator and it seems to work just fine.

The only change I would recommend making would be:

localNotification.repeatInterval = NSCalendarUnitWeekOfYear;

which I found in this very related question.

Also, the compiler will complain if you use lines like:

[nowComponents setMinute:08];

(as it interprets that as an octal number instead of an integer). Don't use leading zeros. Do something like:

[nowComponents setMinute:8];

Don't forget to ask your user to enable notifications, otherwise they simply won't appear.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215