我试图使用此代码每5秒触发一次本地通知

时间:2014-01-24 09:04:48

标签: ios iphone uilocalnotification localnotification

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
if (localNotification == nil)
    return;
//localNotification.fireDate = [NSDate dateWithTimeInterval:timeInterval sinceDate:now];
localNotification.fireDate = [NSDate date];
localNotification.repeatInterval = 5*NSSecondCalendarUnit;
localNotification.alertBody = @"Your alert message";
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

此代码在前5秒后生成通知,然后返回NSMinuteCalendarUnit,我一直试图解决此问题,但没有帮助。

我想每隔5秒设置一次通知然后它应该触发它,直到我强行想要停止它。

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

repeatIntervalUILocalNotification属于NSCalendarUnit类型而非时间间隔。您只能将NSCalendarUnit枚举中的值指定给它。

如果您想每5秒触发一次本地通知,则需要设置多个通知。

答案 1 :(得分:1)

这是代码。 每5分钟而不是每周使用一次。

-(void)setLocalNotificationwithOptions :(NSDictionary *)launchOptions
{
     UILocalNotification *localNoti = [launchOptions  objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNoti) {
    NSLog(@"Notification:%@",localNoti);
}

[[UIApplication sharedApplication] cancelAllLocalNotifications];

NSCalendar *gregCalendar12 = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *dateComponent12 = [gregCalendar12 components:NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:[NSDate date]];


[dateComponent12 setWeekday:7];
[dateComponent12 setHour:14];
[dateComponent12 setMinute:46];

UILocalNotification *notification12 = [[UILocalNotification alloc]init];
[notification12 setAlertBody:@"ENJOY YOUR WEEKEND!"];
[notification12 setFireDate:[gregCalendar12 dateFromComponents:dateComponent12]];
notification12.repeatInterval = NSMinuteCalendarUnit;
[notification12 setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] scheduleLocalNotification:notification12];
}

希望这会对你有所帮助。谢谢..

答案 2 :(得分:0)

如果你想每5秒重复一次计时器, UILocalNotification每个声音允许持续30秒。 所以在你的目录中放一个30秒的声音, 然后

[[UIApplication sharedApplication] cancelAllLocalNotifications];
NSDate *date = "set your notification date"
for (int i = 0; i < 10; i++){
    NSDate *repeatTime = [date dateByAddingTimeInterval:300 * i];
    notification.fireDate = repeatTime;
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}