【问题标题】:iPhone: How to set repeat daily/hourly local notification?iPhone:如何设置重复的每日/每小时本地通知?
【发布时间】:2010-08-06 19:03:19
【问题描述】:

我想测试添加本地通知。我希望它每天/每小时重复一次。我该怎么做?

NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

 // Get the current date
    NSDate *now = [NSDate date];

 // Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit |       NSMonthCalendarUnit |  NSDayCalendarUnit )
           fromDate:now];

NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit)
           fromDate:now];


 // Set up the fire time
NSDateComponents *dateComps = [[NSDateComponents alloc] init];

[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];

[dateComps setHour:[timeComponents hour]];
 [dateComps setMinute:[timeComponents minute]];
 [dateComps setSecond:[timeComponents second]+10];

 // Notification will fire in one minute

NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;

localNotif.fireDate = itemDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];

 // Notification details
localNotif.alertBody = @"Hello World";

 // Set the action button
localNotif.alertAction = @"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;

applicationIconBadgeNumber++;

localNotif.applicationIconBadgeNumber = applicationIconBadgeNumber;

 // Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];

【问题讨论】:

  • 您可以尝试正确格式化您的代码。

标签: iphone ios4 local notifications repeat


【解决方案1】:

如果你想在每天的特定时间设置通知......那么你需要设置通知 repeatInterval 属性。它的iOS句柄;关于通知的自己的。只需添加这一行……​​你错过了。否则,您的代码很好并且可以工作。

notif.repeatInterval = NSDayCalendarUnit;

【讨论】:

  • 我们可以在 NSDayCalendarUnit 中使用随机时间吗?我想每天随机进行一次本地通知...请帮助
  • @shaqirsaiyed:您可能必须手动创建每个随机天的触发时间,这不是正常的“重复间隔”。
【解决方案2】:

如果您使用 dateByAddingComponents:toDate:options:,您的代码会简单得多。

(dateByAddingTimeInterval:不能正确处理日历,例如时区更改。)

如果您希望它重复,我认为您必须添加几个,或者在您的应用下次启动时重新添加它们。否则,每秒重复的通知会非常烦人。

【讨论】:

    【解决方案3】:
    【解决方案4】:
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil) return;
    
    NSDate *fireTime = [[NSDate date]   dateByAddingTimeInterval:900]; // 15 minutes
    
    localNotif.fireDate = fireTime;
    localNotif.alertBody = @"15 min reached";
    localNotif.repeatInterval=kCFCalendarUnitMinute;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多