【问题标题】:UIApplicationLaunchOptionsLocalNotificationKey always null - iOSUIApplicationLaunchOptionsLocalNotificationKey 始终为空 - iOS
【发布时间】:2016-03-27 10:03:26
【问题描述】:

我有一个使用本地通知的 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 及更高版本。

感谢您的宝贵时间,丹。

【问题讨论】:

  • 你是怎么发现通知总是null的?您是否在调试模式下从 Xcode 运行应用程序?默认情况下没有通知开始
  • @Azat 我尝试在 uialertview 中显示通知对象。
  • 当应用程序没有在后台运行并且用户点击通知时,应用程序将被启动并且通知将具有价值。确保用户点击通知
  • 请确保用户点击通知,同时打印launchOptions字典以查看是否有任何值
  • @user1046037 可能是因为我的代码正在调用来自self.myViewController 的方法,而此时应用程序尚未加载?

标签: ios objective-c uilocalnotification appdelegate uiapplicationdelegate


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我不知道这将如何解决问题,我试图在应用程序打开时调用一个方法。我真的不认为这会解决我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2017-07-31
    • 2019-07-18
    • 2019-08-18
    相关资源
    最近更新 更多