【问题标题】:iPhone local notification at particular time特定时间的 iPhone 本地通知
【发布时间】:2013-04-10 02:31:40
【问题描述】:

我想每周晚上 10 点(不限国家/地区)发出通知。我需要使用时区吗?目前我正在使用下面的代码每周触发通知,但是如何在晚上 10 点准确触发通知。

NSDate *date = [NSDate date];
NSDate* myNewDate = [date dateByAddingTimeInterval:7*24*60*60];    
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = myNewDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.repeatInterval = NSWeekCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
[localNotification release];

【问题讨论】:

    标签: iphone notifications


    【解决方案1】:

    我认为将您的 fireDate 设置为您想要收到通知的那一天(而不是“一周后”)的 22:00 会满足您的需求。您可能希望使用 NSCalendar 来执行此操作。

    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    NSDate *currentDate = [NSDate date];
    NSDate *fireDate = nil;
    
    [dateComponents setDay:3];  // ...or whatever day.
    [dateComponents setHour:22];
    [dateComponents setMinute:0];
    
    fireDate = [gregorian dateByAddingComponents:dateComponents
                                          toDate:currentDate 
                                         options:0];
    
    [localNotification setFireDate:fireDate];
    [dateComponents release];
    

    【讨论】:

      【解决方案2】:

      我进行了这些更改并且效果很好...

      NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
      NSDate *currentDate = [NSDate date];
      NSDate *fireDate = nil;
      
      //Getting current Hour
      NSDateComponents *components = [[NSCalendar currentCalendar] components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:currentDate];
      NSInteger hour = [components hour];
      NSInteger minute = [components minute];
      
      [dateComponents setDay:7];//After 1 week
      [dateComponents setHour:22-hour-1];  //Calculating Remaining time for 10PM && "-1" because i am adding 60 min
      [dateComponents setMinute:60-minute];
      
      //Adding remaining time to current Time
      fireDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents
                                                    toDate:currentDate 
                                                   options:0];
      [localNotification setFireDate:fireDate];
      

      【讨论】:

        猜你喜欢
        • 2016-11-06
        • 2018-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        相关资源
        最近更新 更多