Question

I'm looking for a way to retrieve the UIApplicationLaunchOptionsLocalNotificationKey on iOS that doesn't involve using the application delegate, i.e. I don't want to have to implement the following:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UILocalNotification *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotification != nil)
    {
        // Process notification
    }
}

I'm trying to create a helper library that needs information about the startup notification. Is there anyway of doing this? Can I retrieve the launch options via another method at a later point in the application process?

Was it helpful?

Solution

You can add yourself as an observer of the UIApplicationDidFinishLaunchingNotification notification which will be posed by the application and contains the information you are looking for.


As @Stavash suggests, there are limitations. For the first launch you won't be able to pick this notification up because the instance of your library won't be created (your class would need to be in the root XIB). But, this notification will also be sent when the app is re-opened for local / remote notifications.

OTHER TIPS

Use a AppDelegate category and inside the +load method of your category add an observer for UIApplicationDidFinishLaunchingNotification. For the observer class you cannot use "self" but you will have to use a singleton object. Here are exact steps to get it done.

  1. Add a category for your AppDelegate. Eg : @interface AppDelegate (notification).
  2. Implement the +load method in your category. When the app is launched, it will start calling +load method of all the classes that get loaded. This includes your categories also.
  3. Create a Singleton class with a method that will receive the NSNotification. So implement a signature like this - (void)appDidLaunch:(NSNotification *)notification; in your singleton class.
  4. Inside the +load method, add an observer for the notification "UIApplicationDidFinishLaunchingNotification".
  5. Make the singleton object as your observer for this notification.
  6. Add your breakpoints in your +load and appDidLaunch methods to see the sequence of methods being called. You will get the launchOptions also in your observer callback method.

The other way to do it would be to Swizzle the AppDelegate's init method with a swizzle_init method. That way you can avoid the Singleton object and define your "appDidLaunch" observer method inside your AppDelegate's category. In that case you can set 'self' as your notification's observer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top