Ios UILocalNotification和UISwitch记住状态

Ios UILocalNotification和UISwitch记住状态,ios,xcode,Ios,Xcode,我做了一个UISwitch,当它打开时,我的应用程序以重复间隔发送10个通知。一切正常。但问题是,当我想保存并加载UISwitch时,UILocalNotification不再被发送 这是我的代码: 要保存UISwitch状态和通知启动: - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; BOOL test= [[NSUserDefaults standardUserDefaults]

我做了一个UISwitch,当它打开时,我的应用程序以重复间隔发送10个通知。一切正常。但问题是,当我想保存并加载UISwitch时,UILocalNotification不再被发送

这是我的代码:

要保存UISwitch状态和通知启动:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
    NSLog(@"%@",test?@"YES":@"NO");
    [self.alarmSwitch setOn:test animated:YES];
}

- (void) switchIsChanged:(UISwitch *)paramSender{

    if ([paramSender isOn]){



            [[NSUserDefaults standardUserDefaults] setBool:self.alarmSwitch.on forKey:@"switch"];
            [[NSUserDefaults standardUserDefaults] synchronize];






            notification1 = [[UILocalNotification alloc]init];
            notification1.fireDate = [NSDate dateWithTimeIntervalSinceNow:5.0];
            [notification1 setAlertBody:@"U moet uw voeten controleren!"];
            [[UIApplication sharedApplication] scheduleLocalNotification:notification1];


            notification1.fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
            [[UIApplication sharedApplication] scheduleLocalNotification:notification1];


        }
}
我如何以另一种方式保存UISwitch的状态以获得此工作?或者有其他解决方案来解决这个问题吗?

您的开关已更改:当您以编程方式设置on状态时,方法不会触发。我建议将处理通知的代码移出switchIsChanged:方法。例如:

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    BOOL test= [[NSUserDefaults standardUserDefaults] boolForKey:@"switch"];
    NSLog(@"%@",test?@"YES":@"NO");
    [self.alarmSwitch setOn:test animated:YES];

    // initially detect if we should fire the bnotifications
    if ([self.alarmSwitch isOn]) {

        [self fireNotifications];

    }

}

-(void)switchIsChanged:(UISwitch *)paramSender{

    [[NSUserDefaults standardUserDefaults] setBool:paramSender.on forKey:@"switch"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    if ([paramSender isOn]){

        [self fireNotifications];

    }
}

-(void)fireNotifications {

    notification1 = [[UILocalNotification alloc]init];
    notification1.fireDate = [NSDate dateWithTimeIntervalSinceNow:5.0];
    [notification1 setAlertBody:@"U moet uw voeten controleren!"];
    [[UIApplication sharedApplication] scheduleLocalNotification:notification1];

    notification1.fireDate = [NSDate dateWithTimeIntervalSinceNow:10.0];
    [[UIApplication sharedApplication] scheduleLocalNotification:notification1];

}

注意:您可能必须确保通知不会触发多次,这可能会导致错误,因为ViewWillDisplay:可以多次调用。

我遇到了您可能遇到的问题。。。如何修复此问题?添加一个布尔变量以指示是否已触发通知。在fireNotifications中,检查以确保以前没有触发过通知。如果没有,则激发它们并将布尔值设置为“是”。当开关更改为off时,将此布尔值设置为NO,因为通知已关闭。我对此有点了解,但不太了解。。你能给我发一封解释清楚的电子邮件吗?柱花草。apple@gmail.com谢谢