iOS从非运行状态启动应用程序后处理通知

时间:2012-09-05 07:22:23

标签: objective-c ios uilocalnotification uiapplication

我一直在尝试处理在我的应用中接收通知,但它并没有真正解决。

当我使用didReceiveLocalNotification:(UILocalNotification *)notification时。我可以接收并使用用于进入应用程序的通知,没有任何问题

但是,此功能仅在应用已正在运行时激活(有效,无效,后台,可能已暂停,但我尚未尝试过)。

现在,有一个函数didFinishLaunchingWithOptions:(NSDictionary *)launchOptions,您可以使用[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]返回UILocalNotification。

但是,当您从未运行状态启动应用时,不会触发此事件。然后LocalNotification打开应用程序,但我无法以任何方式使用它。

现在,我的问题是:如何让它工作,以便我可以在应用处于未运行状态时从通知启动应用时接收和处理通知?是也许我在这里做错了什么?

以下是我的应用程序中的一些示例代码:

首先,didFinishLaunchingWithOptions函数,不幸的是,它不起作用。函数[sharedLocalNotificationsInstance processNotification:notification]永远不会启动...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

LocalNotificationsController *sharedLocalNotificationsInstance = [LocalNotificationsController sharedLocalNotificationsInstance];
[sharedLocalNotificationsInstance checkNotifications];

UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if ( notification != nil ) {

    // Process the received notification
    [sharedLocalNotificationsInstance processNotification:notification];

    application.applicationIconBadgeNumber = 0;
}

return YES;
}

第二段代码:didReceiveLocalNotification函数,完美运行:我收到通知,[sharedLocalNotificationsInstance processNotification:notification]工作正常。

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{

// Used when the application launches from a notification
LocalNotificationsController *sharedLocalNotificationsInstance = [LocalNotificationsController sharedLocalNotificationsInstance];

// Process the received notification
[sharedLocalNotificationsInstance processNotification:notification];
}

2 个答案:

答案 0 :(得分:4)

这是iOS处理本地通知的方式。这取决于您的应用的状态,例如活动,在后台运行,或尚未启动。 iOS将调用didFinishLaunchingWithOptions或didReceiveLocalNotification,或者根本不会触及您的应用。

请参阅此文章以获得澄清 - http://www.thekspace.com/home/component/content/article/62-uilocalnotification-demystified.html

答案 1 :(得分:1)

<Matrix-Morpheus-Meme title="WHAT IF I TOLD YOU">

当应用程序从“未运行”状态启动时,因为用户点击了本地通知警报,该应用程序已由iOS启动,而不是由Xcode启动,因此它不会在调试器下运行。你不能在它内部断点,NSLog()也不能向Xcode控制台发送任何东西。使用UIAlertController进行测试。

</Matrix-Morpheus-Meme>