Detect if app is not opened via push notification in iOS?

I took this solution from another stack overflow post to detect if the app is opened via push notification:

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    print("Push notification received: \(data)")
    if #available(iOS 9, *) {
    if let type = data["type"] as? String, type == "status" {
        // IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
        if application.applicationState != UIApplicationState.background && NSDate().timeIntervalSince(wakeTime as Date) < 0.1 {
            // User Tap on notification Started the App
            sendPushStatistic()
        }
        else {
            // DO stuff here if you ONLY want it to happen when the push arrives
        }
    }
    else {
    }
    }
}

Now i wonder how to find out if the app was opened (cold start and from background) without clicking on a push notification but via app icon or from the running apps view?

Upvotes: 2

Views: 858

Answers (1)

Zog
Zog

Reputation: 1143

One way to do this would be to add a boolean in your above function that states if it was opened by push notification.

Then in your viewdidLoad you can check the value of this boolean.

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
     print("Push notification received: \(data)")
     if #available(iOS 9, *) {
     if let type = data["type"] as? String, type == "status" {
         // IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
         if application.applicationState != UIApplicationState.background && NSDate().timeIntervalSince(wakeTime as Date) < 0.1 {
             // User Tap on notification Started the App
             sendPushStatistic()
         } else {
             pushNotificationLaunch = true
         }
     }
}

}

Then in the viewDidLoad function you can create an if statement to see if the created variable is true.

override func viewDidLoad() {
    super.viewDidLoad()
    
    if pushNotifcationLaunch = false {
         //Code for did launched via app click.
    }
}

Upvotes: 2

Related Questions