在我的应用程序中使用UILocalNotifications.But我的要求是,我想取消重复的通知。
这里我的代码是.....
-(void)LocalNotificationMethod{
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = self.selectedDate;
NSLog(@" self.selectedDate %@", self.selectedDate);
// Break the date up into components
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// 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]];
// Notification will fire in one minute
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:[timeComponents second]];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
NSLog(@"itemDate %@",itemDate);
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
NSLog(@"itemDate %@", localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = [_titleTextFieldObj text];
// Set the action button
localNotif.alertAction = @"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber =[[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
NSLog(@" localNotif.applicationIconBadgeNumber ++ %ld", (long)localNotif.applicationIconBadgeNumber );
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:[_titleTextFieldObj text] forKey:@"someKey"];
localNotif.userInfo = infoDict;
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
//UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];
NSLog(@"notif %@",notificationArray);
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
我是Objective-c的新手。我不知道在哪里写代码不允许重复通知。任何人都可以帮我解决这个问题。
先谢谢..
答案 0 :(得分:1)
本地通知具有userInfo
属性,您可以使用该属性放置一些自定义信息,并可用于配对通知。我建议您使用此信息插入包含通知类型的NSDictionary
。例如:
NSString *newNotificationType = @"my_notification";
newNotification.userInfo = @{@"notification_type_key":newNotificationType};
然后,在您实施此操作后,您可以创建一个检查,如果此类通知已存在,并取消上一个或取消创建新通知:
for(UILocalNotification *notification in [[UIApplication sharedApplication] scheduledLocalNotifications])
{
NSDictionary *userInfo = notification.userInfo;
if([userInfo isKindOfClass:[NSDictionary class]] && [userInfo[@"notification_type_key"] isEqualToString:newNotificationType])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}
}