2

I need to know whether my app is brought to foreground through interaction with a push notification or manually by a users click on the app.

If you open an app from the background manually "applicationWillEnterForeground" is called. If you open the app from the background through a push notification, "applicationWillEnterForeground" is called, followed by "didReceiveRemoteNotification".

Now i want to make an alamofire request inside of the app delegate to my backend, whenever i am certain that it was opened due to push or not (statistics, do users interact with our push messages).

Is there a method that is called after all those i listed up? If so i could in that place check if it was a push or not and send it away. Or is there a better way to tackle this?

Jochen Österreicher
  • 683
  • 2
  • 11
  • 25

2 Answers2

2

When the app was in the background, you can handle the notification through "didReceiveRemoteNotification".

If it was not running at all and the user started it by clicking on the notification banner, you have to check the launch options:

    if let launchOptions = launchOptions {
        if let notificationInfo = launchOptions[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable : Any] {
            // Handle notificationInfo
        }
    }

in the method "application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?)" in AppDelegate.

user3581248
  • 964
  • 10
  • 22
  • Ok look. I have a rest-api i need to call. OpenedViaPush() or OpenedManually(). The code you show i already use to check it for a coldstart of the app. Now the app is in the background and is reopened. You can indeed check for didReceiveRemoteNotification. But if you want to track if it was opened from background manually too, it does not work because then 2 methods are called. applicationWillEnterForeground and then didReceiveRemoteNotification. – Jochen Österreicher Feb 06 '17 at 14:36
  • You don't have to care about the applicationWillEnterForeground method for the scenario where the app was in the background. Just implement what you need in didReceiveRemoteNotification. Maybe [this thread](http://stackoverflow.com/questions/5056689/didreceiveremotenotification-when-in-background) will be helpful. – user3581248 Feb 06 '17 at 14:46
  • and if you did not received a remote notification but simply opened the app from the background? didReceiveRemoteNotification is only called when you receive a notification. i need a way to do both. – Jochen Österreicher Feb 06 '17 at 14:49
1

Found something that is called afterwards:

func applicationDidBecomeActive(_ application: UIApplication)

here i can fire the request to my backend, having used

didReceiveRemoteNotification

before to figure out if it was opened through a push or not.

Jochen Österreicher
  • 683
  • 2
  • 11
  • 25