How do I tell if my iPhone app is running when a Push Notification is received?

前端 未结 5 486
栀梦
栀梦 2020-12-04 14:39

I am sending Push Notifications to my iPhone app, and I\'d like a different set of instructions to execute depending on whether the app is already launched or not. I\'m new

5条回答
  •  情深已故
    2020-12-04 15:31

    Depending upon what you mean by "launched", you are either looking for:

    • Kevin's answer above (differentiates between launched or not launched)
    • or this (differentiates between suspended or active, but already launched):

    Use a flag that is set true when the application becomes active, and false when the application is not active.

    Flag (in header file [.h]):

    BOOL applicationIsActive;
    

    Code (in implementation file [.m]):

    - (void)applicationDidBecomeActive:(UIApplication *)application {
        applicationIsActive = YES;
    }
    
    - (void)applicationWillResignActive:(UIApplication *)application {
        applicationIsActive = NO;
    }
    
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    {
        if (applicationIsActive) {
            // Handle notification in app active state here
        }
        else {
            // Handle notification in app suspended state here
        }
    

    This works because when the application is suspended, the OS calls "applicationDidReceiveRemoteNotification" before it calls "applicationDidBecomeActive" during the "wake-up" process.

    The "complete" answer is actually Kevin's answer plus this answer.

    Hope this helps.

提交回复
热议问题