UIApplicationLaunchOptionsLocalNotificationKey always null - iOS

核能气质少年 提交于 2019-12-12 19:06:35

问题


I have an iOS application which uses local notifications. When the app is running in the background or is active, I use the application didReceiveLocalNotification methods and that works great. But when the app is closed (not running in the background), I use the application didFinishLaunchingWithOptions method to control what happens when the notification is handled.

However, the problem I have is that the notification is always (null) in the didFinishLaunchingWithOptions method.

Here is my code:

-(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;
}

Am I missing something here? I have asked the user for permission first and have the correct code to get the notification object. My app is built for iOS 9 and higher only.

Thanks for your time, Dan.


回答1:


Display the value launchOptions in an alert view to see if there is any value.

If the value is not nil, then probably your UI code gets executed in the background thread.

Ensure all UI code is executed in the main thread as shown below:

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

This is important when you use asynchronous calls in your app.




回答2:


Implement your code in applicationWillTerminate rather than didFinishLaunchingWithOptions. Because when the app terminated then execute the applicationWillTerminate method.

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


来源:https://stackoverflow.com/questions/36246104/uiapplicationlaunchoptionslocalnotificationkey-always-null-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!