Easy way to see (and debug) UILocalNotifications

It doesn’t take a lot of code to create a UILocalNotification but when you have multiple of them and you’re doing a lot of calendar math and things start getting hairy. To demystify that experience I created a project with a UITableViewController that prints out all of the current UILocalNotifications.

We’ll create 3 local notifications 1 minute apart for the next 3 minutes with these calls:

   [self createLocalNoticationAt:[[NSDate date] dateByAddingTimeInterval:60] withTitle:@"Every Minute 1!"];
    [self createLocalNoticationAt:[[NSDate date] dateByAddingTimeInterval:120] withTitle:@"Every Minute 2!"];
    [self createLocalNoticationAt:[[NSDate date] dateByAddingTimeInterval:180] withTitle:@"Every Minute 3!"];

Continue reading

Getting the Day of the Week from an NSDate

I am trying to get a custom day of the week format like this: Su, M, T, W, Th, F, S.

I’d really like to be able to compare numbers and get 0-6 instead of the full name(Wednesday) or the 3 letter day (Wed). I found this great resource for the NSDateFormatter codes. It turns out that ‘E’ is the 3 letter name and just ‘e’ is the number! The problem I found was that ‘e’ was not zero based, so I had to put a pad into my NSArray that gives my custom weekday string.

	NSDate *now = [NSDate date];
	NSDateFormatter *nowDateFormatter = [[NSDateFormatter alloc] init];
	NSArray *daysOfWeek = @[@"",@"Su",@"M",@"T",@"W",@"Th",@"F",@"S"];
	[nowDateFormatter setDateFormat:@"e"];
	NSInteger weekdayNumber = (NSInteger)[[nowDateFormatter stringFromDate:newDate] integerValue];
	NSLog(@"Day of Week: %@",[daysOfWeek objectAtIndex:weekdayNumber]);

Output (It’s Wednesday):
Day of Week: W

Walking through the code I created a date named ‘now’. Then I created an NSDateFormatter followed by an NSArray of the custom daysOfWeek. I’m using Objective-C literals so I don’t need to end in ‘nil’. I also added a string for the zero element as this output is not zero based so it will never be zero, but it will go from 1-7 for Sunday-Saturday. I then use the format string of @”e” to get just that number and in the next line I create an NSInteger and it’s not a pointer because NSIntegers is basically just a C int. The NSDateFormatter will return a string no matter what and since I know I’m getting a number I just use the NSString ‘integerValue’ to cast and it returns an NSUInteger. NSUInteger is an ‘unsigned int’ variable and NSInteger is just an ‘int’. I could have used either but these numbers will always be small so an NSInteger works just fine.