How to detect if user navigates away from my app in iOS? - ios

I am trying to develop an app which helps people focus. Essentially, users start a session in which they would like to focus. This session lasts as long as the user does not open another app (for example, the user cannot open Facebook). If the user does so, the session is marked as a failure. Users try to last as long as possible.
The issue I see is that iOS does not allow apps to run for more than 3 minutes once the screen turns off. That means that a user can start a session, then put the phone down for 3 or more minutes, and when they unlock the phone, they are presented with their home screen. The app has been killed. A user is then free to roam around and look at any other app, defeating the purpose of my app.
I could use a timer running on a server to maintain overall session duration, and resume the session once the user reopens the app, but this does not solve the issue of users being able to roam before reopening the app.
Are there any ways to get around iOS killing my app? The behavior I want is:
1) User starts session.
2) Session timer begins.
3) If user navigates away from app, session terminates after 30 second warning.
4) If user locks phone, app still runs.
5) When user unlocks phone, app is displayed (not homescreen). Thus, the termination logic is the same.
Thanks!

You can use an observer (add it to your ViewController's viewDidLoad):
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil)
And the function will look like this:
#objc func applicationWillResignActive(notification: NSNotification) {
// do something
}

Related

App Tracking Transparency reset after user choice

I've just implemented the ATT request in my applications. It appears at the app first opening but I would like to show it again if the user wants to change his preferences from the app settings (internal).
I tried to call the requestTrackingAuthorization method again but it enters immediately to the completion handler. Is there a way to reset the status?

Automatically log out user when they leave the iOS app

I have an in-house app which is used by staff but the chances are the device it is used on could become consumer facing. With that in mind I want to ensure that should the staff forget to logout when they switch apps or just reopen the app that I have a command in there to effectively log them out.
After researching I think the best way for me would be to use:
optional func applicationWillEnterForeground(_ application: UIApplication)
and then force the app to go to the login page or the reverse so that when app enters background it forces the app to the logout URL.
Which do you think would be best and how can I use that command to then add in the chosen URL as described above?
So, while I agree with #Rakesha-Shastri in that ""app enters background it forces the app to the logout URL" This seems like bad UX. The first one where you display the login page on returning from background seems fine. It is important that the user is able to resume his work where he left off after logging in again," there does need to be a way, in-case a user is gone too long, that the credentials have passed. It seems in your case, that every time the user LEAVES or CLOSES the app, you want this to be unauthenticated. What if the user gets a phone call? Should it do that? You may want to use Timer, of say some period of time, 2-5 minutes maybe.
Any who, what you can do is force the user to have to RESTART the app, by either presenting a controller that has NO CAPABILITY of going anywhere, therefore forcing a restart, or providing a button that sends them to a login screen you have implemented.
Note:
I would definitely indicate to the user, "due to purposes of security, each time you exit the app, it requires an authentication to re-access. Please log back in". Then provide a button to the login screen.
As you did not provide code, and I'm not going to do this for you, a direction to take this would be to utilize optional func applicationWillEnterForeground(_ application: UIApplication) alongside with getting the current UIViewController. I would google how to do that. Then from there, you can create a new UIViewController that presents this button back to the login screen.

How to open a Swift App from same screen after phone settings configurations [duplicate]

Currently, when I change the camera permissions for my app in Settings, then navigate back to my app, the app will force a refresh and I will lose my place in the app. I follow these steps exactly:
Open an app that uses the camera permission.
Navigate to some screen within the app (so you can visibly see the refresh later)
Go to the Settings app, navigate to the app's settings, and toggle
the camera permission
Double click home and go back to the app.
After a few seconds, it will refresh, bringing you back to the
first screen
Note: I'm using an iPhone 6 running iOS 8.4
I've noticed this behavior on all apps that have the camera permission. My question is:
Is there some way to prevent the app from refreshing/restarting (on resume) after changing the camera permission? It doesn't seem to happen when you toggle location services, for example, and from a usability perspective this is horrible.
User scenario: If a user navigates deep into your app, then needs to change the camera permission (because say they accidentally clicked no last time), they will be forced to navigate back to that screen when they return. This is especially harmful for an app trying to sell you something, or sign you up for a new account. They might try to introduce a new feature where you can use the camera to take a profile picture or scan your credit card. Because the user didn't know about this feature, they might have previously denied camera access, but now want to enable it. After trying to reenable, they come back to your app to find they have to spend 5+ minutes signing up / making a purchase, again! After that, even I would probably give up.
I'm sure that there is no other ways to prevent restarting app. Actually you will get a SIGKILL message but no Crash log when toggling settings. See below links-
https://devforums.apple.com/message/715855
https://devforums.apple.com/message/714178
The only way to prevent this scenario is to save the previous state of you application while terminating.
Store app your current data into a json/plist/NSUserDefaults/archive user model at applicationWillTerminate: method and
restore saved data at applicationWillEnterForeground:
For example- #SignUpViewController register for UIApplicationWillTerminateNotification which will fire when the app is about to terminate. Store user information there.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name: UIApplicationWillTerminateNotification object:nil];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
// store your data here
}
Hope this will help you:)
The accepted answer is correct, however the workaround does not appear to work in the current version of iOS (9.2) - the application seems to terminate before UIApplicationWillTerminateNotification is fired. However by listening to UIApplicationDidEnterBackgroundNotification, the same can be achieved. e.g in Swift, put this in viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "enteringBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
and have a function like this:
func enteringBackground(sender:AnyObject){
// Save application state here
}

objective-c differentiate between alert message and task switcher in applicationWillResignActive

I am trying to run some code during the applicationWillResignActive when the user opens the task switcher and it has worked fine until I began using bluetooth in my app.
When bluetooth tries to connect to a device it shows an alert window asking if the user wants to pair the device. This alert is enough to trigger the applicationWillResignActive method and then runs my code for when the app is being navigated away from (task switcher). This causes a large problem since the code I intend to run when switching away, turns off some much needed functionality within the actual app. So once they press "pair" or "cancel" on that alert, all of my app stops functioning as it should because the app has lost focus.
I have tried to detect the state of the application during this time with this... NSUInteger state = [[UIApplication sharedApplication] applicationState]; thinking of course that it would be considered active when the alert pops up and inactive when in the task switcher. However, this was not the case it shows up as active for both use cases.
Update #1
The question...
How can I differentiate in the application between the app causing a system level inactive focus state like running code to connect to bluetooth, versus the user causing the system level inactive focus like double tapping the home button? All in the efforts to distinguish what is causing the applicationWillResignActive method to fire.
Update #2
The intention of this functionality is to set a flag in NSUserDefaults when bluetooth connects to the device. This flag is being "observed" and used to trigger the changing of view controllers to a page related to this new BT connection. When the user double presses the home button and moves to task switcher I turn off BT and switch to iBeacon so I can notify of events. All is well with this current implementation all bar 1 use case.
If the user hasn't yet connected to the BT device and it connects for the first time and that pairing alert comes up it fires the applicationWillResignActive method just the same as double tapping the home button does. In this method the code then checks for that NSUserDefaults flag to see if it switched on (which by this time it is because the BT has already reached the CBCentralManager's didConnectPeripheral method and turned it on) and if it's on, it turns off BT and switched to scanning for iBeacon. Because the app is still open this obviously causes problems. The app is running so the user see's the BT connect, the new view slide in, the pairing alert come up, then the new view slide right back out and iBeacon starts sending notifications intended for when the user is in the task switcher.
I already have this exact functionality happening in the applicationWillEnterBackground method so that's not the answer. I need to have a way of saying "the app is running right now and we've received an alert instead of double tapping home, so please don't turn off BT and turn on iBeacon yet"
Two possible solutions:
1. The answer may lie in this statement:
When bluetooth tries to connect to a device it shows an alert window asking if the user wants to pair the device.
Your app must do something to cause this alert to appear. You could set a Date field to the current time in your AppDelegate when this happens, and then when you get a call to applicationWillResignActive you can compare that timestamp to the current time, and if it is < 1 second or so, you have a pretty good clue that the bluetooth dialog went up.
Of course, this is not foolproof. As #danh notes in his comment, the design of iOS makes this really difficult. You won't know for sure if the bluetooth dialog went up, or if the user or OS just happened to bring something else to the foreground at the same time. What's more, it's always possible that even if the bluetooth dialog comes up, the user might decide at that very moment to go check his or her email or start browsing Facebook. In that case, it is both true that the bluetooth dialog is what sent your app to the background, AND the user navigated away from the app. Unfortunately, iOS doesn't really give you a way to differentiate the two.
2. You might use a background task to handle your cleanup logic.
You can request up to 180 seconds of background running time after the call to applicationWillResignActive, so you could defer your cleanup tasks until say 175 seconds have passed since your app is resigned to the background. If the user doesn't come back within 3 minutes, it's probably time to do this cleanup anyway. My blog post here shows the basics of setting up a background task. It is specifically targeted to extending beacon ranging time, but you can put whatever logic you want inside the background code block like this:
- (void)extendBackgroundRunningTime {
if (_backgroundTask != UIBackgroundTaskInvalid) {
// if we are in here, that means the background task is already running.
// don't restart it.
return;
}
NSLog(#"Attempting to extend background running time");
__block Boolean self_terminate = YES;
_backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithName:#"DummyTask" expirationHandler:^{
NSLog(#"Background task expired by iOS");
if (self_terminate) {
[[UIApplication sharedApplication] endBackgroundTask:_backgroundTask];
_backgroundTask = UIBackgroundTaskInvalid;
}
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Background task started. Waiting 175 seconds before cleanup.");
[NSThread sleepForTimeInterval:175];
//TODO: perform cleanup code if app is not in the foreground by now
});
}

How can I prevent iOS apps from resetting after changing Camera permissions?

Currently, when I change the camera permissions for my app in Settings, then navigate back to my app, the app will force a refresh and I will lose my place in the app. I follow these steps exactly:
Open an app that uses the camera permission.
Navigate to some screen within the app (so you can visibly see the refresh later)
Go to the Settings app, navigate to the app's settings, and toggle
the camera permission
Double click home and go back to the app.
After a few seconds, it will refresh, bringing you back to the
first screen
Note: I'm using an iPhone 6 running iOS 8.4
I've noticed this behavior on all apps that have the camera permission. My question is:
Is there some way to prevent the app from refreshing/restarting (on resume) after changing the camera permission? It doesn't seem to happen when you toggle location services, for example, and from a usability perspective this is horrible.
User scenario: If a user navigates deep into your app, then needs to change the camera permission (because say they accidentally clicked no last time), they will be forced to navigate back to that screen when they return. This is especially harmful for an app trying to sell you something, or sign you up for a new account. They might try to introduce a new feature where you can use the camera to take a profile picture or scan your credit card. Because the user didn't know about this feature, they might have previously denied camera access, but now want to enable it. After trying to reenable, they come back to your app to find they have to spend 5+ minutes signing up / making a purchase, again! After that, even I would probably give up.
I'm sure that there is no other ways to prevent restarting app. Actually you will get a SIGKILL message but no Crash log when toggling settings. See below links-
https://devforums.apple.com/message/715855
https://devforums.apple.com/message/714178
The only way to prevent this scenario is to save the previous state of you application while terminating.
Store app your current data into a json/plist/NSUserDefaults/archive user model at applicationWillTerminate: method and
restore saved data at applicationWillEnterForeground:
For example- #SignUpViewController register for UIApplicationWillTerminateNotification which will fire when the app is about to terminate. Store user information there.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationWillTerminate:)
name: UIApplicationWillTerminateNotification object:nil];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
// store your data here
}
Hope this will help you:)
The accepted answer is correct, however the workaround does not appear to work in the current version of iOS (9.2) - the application seems to terminate before UIApplicationWillTerminateNotification is fired. However by listening to UIApplicationDidEnterBackgroundNotification, the same can be achieved. e.g in Swift, put this in viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "enteringBackground:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
and have a function like this:
func enteringBackground(sender:AnyObject){
// Save application state here
}

Resources