Zhao Yi Zhao Yi - 7 months ago 24
Swift Question

How to detect whether user click on an alert to open the app?

I want to implement push notification on my app. I am able to send notification to the device. What I want to do is to check whether users open the app by clicking the alert. If yes, I will popup some dialog or show something different based on the content of the alert. I don't know how to do that in my application. I know there is a method as shown below I can override on AppDelegate class. This method will be called when user receives a notification. But I can't know whether user open the app by clicking the alert or not. How can I achieve it?

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])

Answer

check the application state using the following condition, inside didReceiveRemoteNotification method,

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
    {
            if ( application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background ){
                    //Tapped from a notification and the app is in background.
            }else{
                    //App is in Foreground...
            }
    }

Hope this helps.