程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Obj-C - 在特定时间触发本地通知?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到Obj-C - 在特定时间触发本地通知?的问题如何解决?下面主要结合日常开发的经验,给出你关于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 存储为静态属性。

大佬总结

以上是大佬教程为你收集整理的Obj-C - 在特定时间触发本地通知?全部内容,希望文章能够帮你解决Obj-C - 在特定时间触发本地通知?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:-Obj-C