UIApplicationLaunchOptionsLocalNotificationKey 始终为 null - iOS

UIApplicationLaunchOptionsLocalNotificationKey always null - iOS

我有一个使用本地通知的 iOS 应用程序。当应用程序在后台 运行 或处于活动状态时,我使用 application didReceiveLocalNotification 方法并且效果很好。但是当应用程序关闭时(不是运行在后台),我使用application didFinishLaunchingWithOptions方法来控制处理通知时发生的事情。

但是,我遇到的问题是 didFinishLaunchingWithOptions 方法中的通知总是 (null)

这是我的代码:

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

    // Override point for customization after application launch.

    // Register the app for local notifcations.

    if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
    }

    // Setup the local notification check.
    UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

    //UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"options" message:notification delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    //[alertView show];

    // Check if a notifcation has been received.

    if (notification) {

        // Run the notifcation.
        [self.myViewController run_notifcation:[notification.userInfo valueForKey:@"notification_id"]];
    }

    // Ensure the notifcation badge number is hidden.
    application.applicationIconBadgeNumber = 0;

    return YES;
}

我是不是漏掉了什么?我首先征求了用户的许可,并有正确的代码来获取通知对象。我的应用程序仅适用于 iOS 9 及更高版本。

丹,谢谢你的时间。

applicationWillTerminate 而不是 didFinishLaunchingWithOptions 中实现您的代码。因为当应用程序终止时,然后执行 applicationWillTerminate 方法。

 func applicationWillTerminate(application: UIApplication) {
     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
 }

在警报视图中显示值 launchOptions 以查看是否有任何值。

如果该值不为零,那么您的 UI 代码可能会在后台线程中执行。

确保所有UI代码都在主线程中执行,如下所示:

dispatch_async(dispatch_get_main_queue(), ^{ 
//self doSomething (UI Code)
});

当您在应用中使用异步调用时,这一点很重要。