如何使NSUserNotification超时?

时间:2014-09-16 13:47:31

标签: objective-c xcode cocoa notifications timeout

我正在使用这种方法:

NSUserNotification *notification = [[NSUserNotification alloc] init];
            notification.title = @"Title";
            notification.informativeText = @"body";
            notification.soundName = NSUserNotificationDefaultSoundName;

            [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];

如何让它在3秒后超时?

2 个答案:

答案 0 :(得分:5)

将NSTimer设置为在三秒钟后启动,然后使用NSUserNotificationCenter s removeDeliveredNotification删除您的通知。

e.g。使用NSTimer+blocks来实现紧凑性和清晰度:

[NSTimer scheduledTimerWithTimeInterval:3.0 block:^
{
    [[NSUserNotificationCenter defaultUserNotificationCenter] removeDeliveredNotification: notification];
} repeats:NO];

请注意,这不是使用该NSTimer类别的说明或建议 - API不是那么好: - )

答案 1 :(得分:0)

我自己解决了这个问题!我使用usleep()等待,然后在3秒后将其删除。希望这有帮助

            NSUserNotification *notification = [[NSUserNotification alloc] init];
            notification.title = @"Upload Failed!";
            notification.informativeText = @"Error reading data.";
            notification.soundName = NSUserNotificationDefaultSoundName;
            [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
            usleep(3000000); //waits for 3 seconds
            [[NSUserNotificationCenter defaultUserNotificationCenter] removeDeliveredNotification: notification];