简体   繁体   中英

How to show User notification twice on single button click using NSUserNotification?

Let me first describe the scenario then I will describe the issue:

I have created a function that shows a user notification using NSUserNotification

    -(void)notify:(NSString*) message {

    NSUserNotification *notification = [[NSUserNotification alloc] init];
    notification.title = @"TechHeal";
    notification.informativeText = message;
    //notification.soundName = NSUserNotificationDefaultSoundName;

    [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];    
}

I have a button the fetches details from the server. At the begening and at the end of the button click I have called the notification as shown below:

-(IBAction)get2000Rows:(id)sender{

    [self notify:@"Please wait..."];

    //some code that takes a while to run. like 10 minues :P

    [self notify:@"Thanks for waiting..."];

}

Now, the issue is that the first notification "Please wait..." is not getting shown on the button click however the last notification is showing perfectly.

I also tried to call Notify function in a seprate thread but it did not worked as well. (Shown Below)

dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);

    dispatch_async(backgroundQueue, ^{

        [self notify:@"Please wait..."];


        dispatch_async(dispatch_get_main_queue(), ^{
        });    
    });

Your help is really appreciated. Thank you in advance.

The problem is that you run your 10 minutes code on the same thread as the UI part of the code. So you should separate those using this:

-(IBAction)get2000Rows:(id)sender{

    [self notify:@"Please wait..."];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        //some code that takes a while to run. like 10 minues :P

        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [self notify:@"Thanks for waiting..."];
        });
    });
}

You can start the timer through NSTimer for remessage

@interface MyClass ()
{
     NSTimer *timer;
}

-(IBAction)get2000Rows:(id)sender{

       [self notify:@"Please wait..."];


       timer = [NSTimer scheduledTimerWithTimeInterval:10.0f
                                                target:self
                                            selector:@selector(timerClick:)
                                            userInfo:nil
                                             repeats:YES];
}

 - (void)timerClick:(NSTimer *)timer {

        [self notify:@"Thanks for waiting..."];
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM