Reputation: 1449
I'm building a calendar app, and I want my users to be able to get notified 30 min before an appointment, or 60 minutes before an appointment. That said, how can I schedule a local notification to fire 30 min before a scheduled time pulled from an array or dictionary? My current code is able to fire a notification from the background at a specific time, but I'm not sure how to call the returned dates set by my user to App Delegate?
E.g. the array data coming from my server:
"Apr 14 2021 12:04 PM",
"Apr 17 2021 12:27 PM"
My code currently in app delegate:
AppDelegate.m
- (void)applicationDidEnterBackground:(UIApplication *)application {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now];
[components setHour:7];
[components setMinute:00];
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = [calendar dateFromComponents:components];
notification.repeatInterval = NSDayCalendarUnit;
[notification setAlertBody:@"Ready to start your day?"];
// notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
Any help on how I should execute this is appreciated! I hope the way I explained what I'm trying to do makes sense.
Upvotes: 0
Views: 319
Reputation: 342
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MMM d yyyy h:mm a";
NSString *dtString = @"Apr 14 2021 12:04 PM";
NSDate *date = [dateFormatter dateFromString:dtString];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
components.minute -= 30;
NSDate *fireDate = [calendar dateFromComponents:components];
Then use fireDate
to set fireDate of notification. I suggest storing dateFormatter
and calendar
as static properties.
Upvotes: 1