ios - 有没有更好的方法来计算重复间隔通知的小时代码的顶部?

标签 ios objective-c uilocalnotification alarm hardcode

<分区>

我已经对这个 Hour 进行了硬编码,以帮助我在每个小时的顶部触发本地通知,但是出了点问题。不过,我不知道这是我测试它的方式、我的 Xcode 行为还是代码本身。无论如何,这是我编写的代码,请看一下,请指导我使用更简单或更好的方法来编写此类代码。谢谢。

NSCalendar *calendar1 = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar1 components:(NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]];
hour = [components hour];
min =[components minute];
sec =[components second];
NSLog(@"hour is %i",hour);

NSLog(@"min is %i",min);

NSLog(@"sec is %i",sec);
if (hour < 24) {
 hour=hour+1;
 } else {
     hour=0;

然后..

[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
NSDateComponents *componentsForReferenceDate = [[NSDateComponents alloc] init];
[componentsForReferenceDate setHour:hour];
[componentsForReferenceDate setMinute:0];
[componentsForReferenceDate setSecond:0];

 NSDate *fireDateOfNotification = [calendar dateFromComponents: componentsForReferenceDate];

// Create the notification

最佳答案

这里有几件事需要考虑:

  • 询问日期时,您无需询问分钟和秒数,因为您无论如何都会将其丢弃。
  • 你或许应该设置一个时区
  • 当小时是 23 时,你将加 1,得到 24,这是不对的
  • 你不需要创建一个新的 NSDateComponents 对象,你可以只配置你拥有的那个

    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    
    NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:[NSDate date]];
    components.hour   = (components.hour + 1) % 24;
    components.minute = 0;
    components.second = 0;
    
    NSDate *fireDate = [calendar dateFromComponents:components];
    NSLog(@"%@", fireDate);
    

使用 % 设置小时可防止我们超过 23

关于ios - 有没有更好的方法来计算重复间隔通知的小时代码的顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14288593/

上一篇:ios - 将对象存储到 NSMutableArray

下一篇:iphone - 模仿照片应用程序的平移行为(速度)

相关文章:

ios - 在第 4 代 iPad 上缩放图像很慢,是否有更快的替代方案?

iphone - OpenGL ES代码修改

ios - 有没有办法让用户选择本地通知的声音?

ios - 如何使用 Storyboard 在消失的导航栏上添加栏按钮项目?

ios - 在 SKShader 中使用父坐标

objective-c - 在 NSTableCellView 上设置背景颜色

iphone - 后台本地通知

iphone - 当应用程序处于工作模式时,UILocalNotification 不会触发

php - 验证 appReceiptStoreURL 返回 21002 状态

ios - 函数 glGenFramebuffers 的隐式声明