微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Obj-C - 在特定时间触发本地通知?

如何解决Obj-C - 在特定时间触发本地通知?

我正在构建一个日历应用,我希望我的用户能够在预约前 30 分钟或预约前 60 分钟收到通知。也就是说,如何安排本地通知在从数组或字典中提取的预定时间之前 30 分钟触发?我当前的代码能够在特定时间从后台触发通知,但我不确定如何将用户设置的返回日期调用到 App Delegate?

例如来自我的服务器的数组数据:

"Apr 14 2021 12:04 PM","Apr 17 2021 12:27 PM"

我的代码目前在应用委托中:

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];
    
    
}

对我应该如何执行此操作的任何帮助表示赞赏!我希望我解释我要做的事情的方式有意义。

解决方法

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];

然后使用 fireDate 设置通知的 fireDate。我建议将 dateFormattercalendar 存储为静态属性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。