macosnsalert

How to close an alert after some time and repeat it every 10 min


In my MAC OSX application. I am throwing a an alert pop up asking user to select yes or no. if user doesnt click any of the choices and may drag it to some corner. So i wanted to autoclose it after some time and again show the same alert. so i can ensure him to take same action. Alert code i am using is

-(bool)VpnStatusUnableToConnect:(NSString *)alertMessage
{
    if (nil != alertMessage) {
        NSImage *alertIcon = [NSImage imageNamed:@"dock-alert"]; //my custom image placed in support files
        NSAlert *alert = [[NSAlert alloc]init];
        [alert addButtonWithTitle:@"Try Again"];
        [alert addButtonWithTitle:@"Cancel"];
        [alert setMessageText:alertMessage];
        [alert setAlertStyle:NSWarningAlertStyle];
        [alert setIcon:alertIcon];
        [[alert window] setTitle:@"VPN Connection Status"];
        [[alert window] setBackgroundColor: NSColor.whiteColor];
        if ( [alert runModal] ==  NSAlertFirstButtonReturn)
        {
            return 1;
        }
        else
            return 0;
    }
    return 0;

}

Solution

  • Modify your code as below and give a try

    -(void)yourAlert{
        NSAlert *alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle: @"OK"];
        [alert setMessageText: @"Attention!!! This a critical Alert."];
        [alert setAlertStyle: NSInformationalAlertStyle];
    
        NSTimer *myTimer = [NSTimer timerWithTimeInterval:3
                                                   target:self
                                                 selector: @selector(killWindow:)
                                                 userInfo:nil
                                                  repeats:YES];
    
        [[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSModalPanelRunLoopMode];
    
        int choice = 0;
        choice = [alert runModal];
        if(choice != 0)
            [myTimer invalidate];
    }
    
    -(void) killWindow:(NSAlert *)alert with:(NSTimer *) theTimer;
        {
    
            NSLog(@"killWindow");
            [[alert window] abortModal];
    
        }