Function call when exiting app, but not locking phone

I am currently trying to develop my first app in xcode and I want a function to run whenever the app i exited. I.e. switching to another app or going to the home screen. But if the phone is locked while in the app I do not want the function to run. I currently use the sceneDelegate and sceneDidEnterBackground, that works for running the function when exiting the app, but it also runs when I lock the phone. I do not want that to happen. How do I go about implementing this feature?

In addition I also want to have a "live notification" showing on the lock screen if you lock the phone from the app, I have not been able to find out how that works either.

Function call when exiting app, but not locking phone
 
 
Q