ios - UIApplicationLaunchOptionsLocalNotificationKey 始终为 null - iOS

标签 ios objective-c uilocalnotification appdelegate uiapplicationdelegate

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

感谢您抽出时间,丹。

最佳答案

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

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

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

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

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

关于ios - UIApplicationLaunchOptionsLocalNotificationKey 始终为 null - iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246104/

相关文章:

objective-c - 全局替换 NSPasteboard.generalPasteboard()

iphone - scrollToRowAtIndexPath :atScrollPosition:animated scrolling too slow

ios - 设备重启时的 LocalNotification

ios - Swift - 交付应用程序上的本地通知图标角标(Badge)编号更新在后台

ios - 更改 UIPickerView 选择指示器的颜色

ios - 如果我的 WidgetKit 正在被使用,如何查询 WidgetKit?

ios - 旋转后 UIWebView 内容未调整到新框架

ios - Swift 4 - 如何使用按钮启用/禁用键盘

objective-c - 使用 NSObject 的哈希创建 NSMutableDictionary 键有什么问题?

ios - UILocalNotification - 需要在警报/通知期间振动更长时间