UIAlertController is automatically dismissing

2019-09-22 12:35发布

问题:

My UIAlertController is disappearing automatically, why?

-(void)marge_carburant{
    NSString *quantite_carburant_reglementaire = [[NSUserDefaults standardUserDefaults] stringForKey:@"quantite_carburant_reglementaire"];


    // PRISE EN CHARGE DU REGLAGE DE LA MARGE CARBU
    if ([quantite_carburant_reglementaire isEqual: @"2"]){
        quantite_reglementaire = 21;
    }
    if ([quantite_carburant_reglementaire isEqual: @"1"]){
        quantite_reglementaire = 0;
   UIAlertController *alert_carbu_reglementaire = [UIAlertController
                                  alertControllerWithTitle:@"ATTENTION"
                                  message:@"Le résultat ne prend pas en compte la quantité réglementaire"
                                  preferredStyle:UIAlertControllerStyleAlert];



  [self presentViewController:alert_carbu_reglementaire animated:YES completion:nil];
  [self performSelector:@selector(dismissTheAlert) withObject:nil afterDelay:3.0];
    }
}
- (void) dismissTheAlert {
     [self dismissViewControllerAnimated:YES completion:^{}];
}

回答1:

Try below one.

3.0 * NSEC_PER_SEC is delay in seconds

[self presentViewController:alert_carbu_reglementaire animated:YES completion:nil];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[alert_carbu_reglementaire dismissViewControllerAnimated:YES completion:^{
    // do something ?
}];
});

You can add a delay in calling marge_carburant function to prevent crash if calling from view did load.