iphone - 在新线程上设置本地通知?

标签 iphone multithreading ios4 nsthread uilocalnotification

我需要知道是否可以创建一个新线程来处理设置本地通知。

我的应用严重依赖于这些通知,因此我希望在手机设置通知时使应用正常运行。

示例:

(现在)

您启动应用程序,应用程序会卡在启动屏幕上以设置本地通知,然后启动。

(我想要)

设置本地通知后,应用程序将启动并可用。

我也需要一些示例代码,请:)

(郑重声明,出于我自己的原因,我每次应用程序进入前台时都会设置 60 个本地通知...)

谢谢!!

最佳答案

是的,这是可以做到的,我一直这样做:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Add the navigation controller's view to the window and display.
    [NSThread detachNewThreadSelector:@selector(scheduleLocalNotifications) toTarget:self withObject:nil];
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;
}

-(void) scheduleLocalNotifications
{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    for (int i = 0; i < 60; i++)
    {
        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
        NSLog(@"Sleepdate is: %@", sleepDate);

        localNotif.fireDate = sleepDate;    

        NSLog(@"fireDate is %@",localNotif.fireDate);
        localNotif.timeZone = [NSTimeZone defaultTimeZone];
        localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"This is local notification %i"), i];

        localNotif.alertAction = NSLocalizedString(@"View Details", nil);
        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 1;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
        [localNotif release];

    }

    [pool release];
}

取 self 现在正在进行的一个项目,我可以确认它按预期工作。

编辑:
scheduleLocalNotifications 中的示例发生泄漏,因为缺少对 NSAutoreleasePool 的处理 - 现在已将其添加到示例中。

关于iphone - 在新线程上设置本地通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4316880/

相关文章:

iphone - 如何在 XCode 4.3 中创建新的 View Controller

ios - 使用AVPlayer播放时如何将音频连接到蓝牙

iphone - 从 NSArray 中随机选择一个 objectAtIndex

iphone - 电影结束后 MPMoviePlayerController 问题

html - 由于 View 宽度,移动设备会拉伸(stretch)屏幕的 div

ios - 交互式推送通知 - 隐藏/显示按钮

Java 8 流并行度 : set number of threads to use?

c# - 用于处理 MySQL 的带有队列的线程

c# - 使用任务工厂存储每个任务的任务完成时间

iphone - iOS4 - 快速上下文切换