这就是我设置本地通知的方式,一切正常。
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:[_datePicker date]];
NSLog(@"%@",[_datePicker date]);
NSDate *fireDate = [gregorianCalendar dateFromComponents:components];
NSLog(@"Fire date : %@",fireDate);
// check if the time is already passed
if ([fireDate compare:[NSDate date]] == NSOrderedAscending)
{
// if it does add 1 day
components.day = components.day+1;
fireDate = [gregorianCalendar dateFromComponents:components];
}
NSLog(@"Fire date : %@",fireDate);
for (int i = 0; i < 7; i++) {
NSDate *scheduleDate = [fireDate dateByAddingTimeInterval:(i * 24.0f * 3600.0f)];
NSDateComponents *componentsForEachDay = [gregorianCalendar components:NSWeekdayCalendarUnit fromDate:scheduleDate];
if (componentsForEachDay.weekday != 7) { // To skip Saturday
localNotification = [[UILocalNotification alloc] init];
localNotification.repeatInterval = NSWeekCalendarUnit;
localNotification.fireDate = fireDate;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.alertBody = @"test";
localNotification.repeatInterval = NSCalendarUnitDay;
localNotification.applicationIconBadgeNumber = 0;
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%i",i] forKey:[NSString stringWithFormat:@"bracletNotif%i",i]];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
我总是只获取userInfo中的最后一个对象..如何将所有scheduleLocalNotification存储在userInfo中以便以后取消? 它的工作原理如何?在每个scheduleLocalNotification我需要之前保存一个对象和密钥?或者我可以将它们全部保存在一个? 因为我已经尝试过这样做,我得到了所有的userInfo对象但是无法删除它们:/
请SOS。
答案 0 :(得分:2)
如果您尝试取消所有braclet
次通知,而不是向他们提供所有不同的键/值,则可以执行以下操作:
localNotification.userInfo = @{@"category": @"bracelet"};
取消:
[[[UIApplication sharedApplication] scheduledLocalNotifications] enumerateObjectsUsingBlock:^(UILocalNotification *notification, NSUInteger idx, BOOL *stop) {
NSDictionary *userInfo;
if((userInfo = [notification userInfo])){
NSString *categoryValue;
if((categoryValue = [userInfo objectForKey:@"category"]) && [categoryValue isEqualToString:@"bracelet"]){
[[UIApplication sharedApplication] cancelLocalNotification: notification];
}
}
}];
我们在这里做的是将所有通知分组到category
:bracelet
。由于未来sdk的变化,我选择了密钥category
。我们可以安排更多通知category
:neckless
然后,如果需要,我们会遍历所有UILocalNotifications
并在通知category
中扫描userInfo
键,如上所示,如果键值等于bracelet
,然后我们取消通知。
if((categoryValue = [userInfo objectForKey:@"category"]) && [categoryValue isEqualToString:@"bracelet"]){
这行代码检查category
的密钥是否存在(即不是nil
),同时将其分配给变量categoryValue
,然后if语句立即检查categoryValue
是否bracelet
1}}等于NSString *categoryValue = [userInfo objectForKey:@"category"];
if(categoryValue && [categoryValue isEqualToString:@"bracelet"]){
它本可以改写为:
{{1}}