我正在创建一个提醒应用程序。在本地通知正在特定时间触发。我还实现了一个用于打开/关闭通知的功能。通知工作正常但是取消功能不起作用。我m使用下面的代码。这段代码有什么问题。请帮帮我。谢谢。
- (无效)SWIT {
if (flag==1) {
//if (toggleSwitch.on) {
toggleSwitch.on=YES;
flag=1;
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// 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];
[dateComps release];
if (localNotif == nil)
return;
localNotif.fireDate = itemDate;
NSLog(@"%@",itemDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];
// Notification details
localNotif.alertBody = @"Tip of the day";
// Set the action button
localNotif.alertAction = @"View";
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
// Specify custom data for the notification
NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
localNotif.userInfo = infoDict;
// Schedule the notification
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(@"it is working");
}
else {
toggleSwitch.on=NO;
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
NSLog(@"it is not working");
}
}
答案 0 :(得分:0)
如果由于flag
var:
// so if flag == 1
if (flag==1) {
toggleSwitch.on=YES;
// the value doesn't change
// you will never reach the else part
flag=1;
当您检测到flag==1
时,请为其指定另一个值,以便下次取消通知时。另外,请不要忘记在else
部分,将flag
放回1
。