如何将本地通知重复间隔设置为自定义时间间隔?

我正在制作一个iPhone应用程序,该应用程序需要本地通知。


在本地通知中,有repeatInterval属性,我们可以将单位重复间隔设置为分钟,小时,天,周,年等。


我希望重复间隔应该是4个小时。


因此,每4个小时就会收到一次本地通知。


我不希望用户为每个设置单独的通知。


我希望用户能够将repeatInterval设置为4小时。


我怎么做?


iphone 


千万里不及你
浏览 669回答 3
3回答

拉莫斯之舞

得到了答案,它是尽可能直接的。您无法创建自定义重复间隔。您必须使用NSCalendarUnit的内置单位时间间隔。我尝试了上述所有解决方案,甚至尝试了其他方法,但是它们都不起作用。我花了很多时间来发现没有办法让它在自定义时间间隔内工作。

尚方宝剑之说

我有一个想法如何做到这一点,我已经在我的项目中实现了首先,使用火灾日期(例如,每分钟)创建本地通知。下一步-使用此通知的唯一ID(如果您以后希望删除它)和您的自定义期限来填充用户信息:-(void) createLocalRepeatedNotificationWithId: (NSString*) Id{&nbsp; &nbsp; UILocalNotification *localNotification = [[UILocalNotification alloc] init];&nbsp; &nbsp; NSTimeInterval your_custom_fire_interval = 60; // interval in seconds&nbsp; &nbsp; NSDate *remindDate = [[NSDate date] dateByAddingTimeInterval:your_custom_fire_interval];&nbsp; &nbsp; localNotification.fireDate = remindDate;&nbsp; &nbsp; localNotification.userInfo = @{@"uid":Id, @"period": [NSNumber numberWithInteger:your_custom_fire_interval]};&nbsp; &nbsp; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];}之后,-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification在您的AppDelegate中实施:从用户信息中获取您的自定义期间。更改下一个时期的开火日期只需再次将其添加到隐藏的通知中即可!NSInteger period = [[notification.userInfo objectForKey:@"period"] integerValue]; //1NSTimeInterval t= 10 * period;notification.fireDate =[[NSDate date] dateByAddingTimeInterval:t]; //2&nbsp;&nbsp;[[UIApplication sharedApplication] scheduleLocalNotification:notification]; //3如果您要删除此通知,请执行UIApplication *app = [UIApplication sharedApplication];NSArray *eventArray = [app scheduledLocalNotifications];for (int i=0; i<[eventArray count]; i++){&nbsp; &nbsp; UILocalNotification* oneEvent = [eventArray objectAtIndex:i];&nbsp; &nbsp; NSDictionary *userInfoCurrent = oneEvent.userInfo;&nbsp; &nbsp; NSString *uid=[NSString stringWithFormat:@"%@",[userInfoCurrent valueForKey:@"id"]];&nbsp; &nbsp; if ([uid isEqualToString:notification_id_to_remove])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Cancelling local notification&nbsp; &nbsp; &nbsp; &nbsp; [app cancelLocalNotification:oneEvent];&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}很重要!-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification当您处于后台时,请勿调用。因此,您必须设置长时间运行的后台任务,在该任务中您将再次创建通知。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS