iOS home button warning, is it possible? - iphone

I really don't think this can be done, but still my boss wants me to provide a link where it says so. What he wants is to add an 'are you sure you want to exit?' warning when the user presses the home button, and if the user says 'no' the app won't go inactive.
It can't be done, can it?

No, you cannot do this - the application has no say in this. Ask your boss whether he has ever seen a single example of an iOS application that would do this. There isn't ... not one I would bet.
The application can continue to execute some functionality in the background - streaming music, getting location information for example, but no application can block the home button. If you could do this, you could block an application from ever closing.
A) You couldn't technically do this and
B) Apple wouldn't allow it to be released on the App Store if that was the distribution route you were taking
If you look at the methods stubs created by XCode when you create an application delegate
-(void)applicationWillResignActive:(UIApplication *)application
-(void)applicationWillTerminate:(UIApplication *)application
That are filled will comments about how you can use this method to pause tasks, disable timers, throttle down frame rates, save data - there is nothing about being able to delay, query the user with an "Are you sure" message.
This whole idea is rather counter to the user-experience of the iPhone/Pad/Pod-Touch.
From the App Store guidelines (slightly abbreviated):
Apps that alter the behavior of switches on the device will be
rejected
This is a proposed change the behavior of the home button - so would be rejected.

This is possible on a jail broken device, using un-aproved API's. The concept is in multiple violations of apple's usage policy however so you would never, ever, ever get an app attempting to implement this in any way on the official app store. Here's just a few reasons:
You can't alter the functionality of any buttons (including the volume buttons, some camera apps used to use them to take pictures, but they got booted from the store as a result).
You can't interfere with standard user interactions with the device. The home button takes people home, you can't prevent that, or ask for confirmation as that would be interfering with the interaction.
There is no public API to detect actual usage of the home button. As such you would need a private API, and you can not use private API's without explicit permission from Apple, which they would never give due to #1 and #2 above.
I'm sure there's plenty of more reasons, but regardless it would be in direct violation of app store policies as well as iOS human interface guidelines.
You can detect when the app is about to lose focus, has lost focus, or could loose focus (such as a phone call is coming in) but you can not alter the flow (i.e. not allow the app to lose focus).
You can continue to execute code in the background within the backgrounding guidelines and limitations. The backgrounded code could submit a notification to the user that would allow them to switch back into the app... that's about as close as you could get, and expect apple to reject you if it happens every time the app closes...

Already answered by numerous others, but no, you can't do this. When the user presses the home button, your application delegate's applicationWillResignActive is called which disables touch events to the application. Then applicationDidEnterBackground is called, which, per the Apple docs:
Your delegate’s applicationDidEnterBackground: method has
approximately 5 seconds to finish any tasks and return. In practice,
this method should return as quickly as possible. If the method does
not return before time runs out, your application is killed and purged
from memory

You need proof to show your boss that obviously isn't an iOS developer.
Apple Human Interface Guide
That should be all the proof you need. But to be clear, Apple will not allow an app to override the home button in any way. You can surely put action sheets or pop ups to warn before logging out, but once the home button is pressed, you are on notice to give up your memory, you are being shut down.

You might want to look into the Store Demo Mode of IOS. This way you can disbale the Home button and lock the device in the first app you start after booting.

I know I'm too late to answer this question.
But I recently came with the issue which Samssonart had.
The answer given by #iandotkelly is deprecated with iOS5. Now none of delegate method will be used to distinguish between locking the device or sending app to background using Home button.
you can now use applicationState variable to define what action is triggered.
applicationState is an inbuilt id provided by appDelegate.
**
if it returns 2 then, it will identify the Home button is pressed
if it returns 1 then, it will identify the lock hardware button is pressed
**
So, in your case you can check out this condition in **applicationDidEnterBackground** method
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(#"decision >> %d",[[UIApplication sharedApplication] applicationState]);
}
Enjoy Programming!

The best reference I can find is this one. It's not quite explicit, but Apple's Human Interface Guidelines have a couple of headings 'Always Be Prepared to Stop', followed by 'Don't Quite Programmatically', which spell out what the home button does and that you shouldn't be implementing your own quitting strategies.

I know this is an old topic, but I just want to update this answer. In iOS 7 this is not working.
So I use screenbrightness when the app will go to the background to identify difference between the Home and Lock button.
-(void)applicationDidEnterBackground:(UIApplication *)application {
if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateInactive) {
NSLog(#"Sleep button pressed");
} else if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
if ([[UIScreen mainScreen] brightness] > 0.0)
NSLog(#"Home button pressed");
else
NSLog(#"Sleep button pressed");
}
}
I hope this is gonna be of any help for in future for anyone

Related

How to detect whether user didEnterBackground because of phone call or click on home button?

We have a multiplayer game and sometimes user quit the game so we would like to know how did user quit the game. Can we use didEnterBackground for that?
We would like to know whether user quit the game by clicking exit button, or by incoming call, or by home button to exit.
When you press home button your application is sent to background and applicationDidEnterBackground will get call first and if it is by call, sms then applicationWillResignActive will get call first.
This is not perfect answer of your question but this might help you in some.
in the appDelegate.m File u have this function:
- (void)applicationDidEnterBackground:(UIApplication *)application
write the code you want in it. (saving data or anything)
First of all, the user interface guidelines forbid quitting an app programmatically and based on what I have read, apps the provide an exit button will be rejected.
If by 'quit the game' you mean something along the lines of 'terminated gameplay', then that should not be a problem.
Also note that pressing the home button does not exit the app. It simply sends it to the background. There does not appear to be any facility to detect why the app left the foreground, which probably means that Apple wants your app to handle all such cases in the same way: by saving state and being prepared to restart where execution left off. Note that an application in the background can be terminated at any time, hence the need to save state.
The answer to your question therefore would seem to be: don't do that.

Programming background behavior when iPhone is locked and user presses power button

Sorry, I am new to iPhone development and my google searches have failed me, so I have had to resort to posting a potentially idiotic question on SO.
I would like to write an app that, when suspended, performs an action when the user presses the home or power button (presumably to unlock the phone). I read the section in the iOS App Programming Guide's App States and Multitasking and the "Processing Queued Notifications at Wakeup Time" discusses handling queued events upon waking up. However, this isn't what I'm after.
I'd like to know if it is possible to:
From the phone sleeping state (I couldn't find a document for phone states, so I am talking about the case where the user presses the power button to turn off the screen), I would like my app to be ready to respond to the event where the user presses the power or home button (to unlock the phone)
I would like my app to respond to the event that occurs when the user unlocks the phone. I found an answer here that's close.
I don't want any funkiness when calls come in, get ignored, etc. :)
From what I can tell, it's a very gray area in the API around locking and unlocking, and I'd like to verify whether or not I'm wasting my time trying to do this.
It looks like I can use the accelerometer to detect when the phone is locked, but I also assume that I won't be able to count on this behavior in all future versions of iOS.
EDIT - I think I can handle the locking and unlocking requirements by assuming that the application has to be running at the time the phone is locked and unlocked, but I still cannot figure out if it is possible to determine #1 above, which is that the power button has been pressed and the unlock screen is displayed. Likewise, I'd like to know if the power button has been pressed again and is no longer displayed (i.e. screen is off).
All of the behaviors for your app being suspended/backgrounded are in the document you referenced. The AppDelegate will receive these messages and pass them on to whatever view you want to listen for them.
-applicationWillTerminate
-applicationWillEnterBackground
-applicationDidBecomeActive
-applicationWillResignActive
You can set up a notification observer in your view if you would like the view to be notified of any of these events. Then just override them or set up a custom method to do any work that needs to be done.
While the Apple docs might be a little foggy at first, all the information is in there to let you know which state your app will go to and how it will be handled. It is up to you to figure out what your app needs to do for each of these events. Hope this helps.

how to catch the power button and home button on iPhone?

Today I went to job interview, I encountered three questions now.they hope i provide some Solutions or
Thinking.
1.when user press Home button,app don't go back the main interface or delay 5 seconds to go back the
main interface.
2. when the screen is black ,how to auto activation screen(how to catch power button press event) .
3.how direct launch my app when iPhone is start-up
My english is very bad, i hope everyone can understand what i said above.Thank you very much
None of these are possible on an iOS device, unless it's jailbroken.
Q1 and Q2: not possible
Q3: The closest you can get to desired behaviour is kiosk (store demo) mode of operation.
See more here:
Lock-down iPhone/iPod/iPad so it can only run one app
It's not exactly what you're looking for - it limits the device to use only certain app - but to my knowledge the only way to auto-start an app without jailbraking the device.
I know that this question is old, but there are easy work arounds for every question on here that work for at least iOS 7+, although there is no way to do question 2 without using private APIs. You can successfully answer questions 1 and 3 with public API answers (although they are admittedly hacky)!!
1. When user presses home button, how do you delay 5 seconds before returning to the main screen?
Oscar Gomez's answer was spot on. While you cannot delay the UI from returning to the home screen without blocking the core run loop (which will get you rejected from the app store), you can use some background process techniques if needed to get your extra 5 seconds, just not with UI.
2. How do you catch the Power Button presses?
This is for sure using a private API, and while you can PROBABLY get into the App Store, you probably won't last long once Apple gets wind of you doing this. It is also a hack. You cannot listen directly to the power button, but you CAN listen to the screen going on or off, or both at once. Here is a small code snippet that I have in an Enterprise App:
Inside UIAppDelegate
static int const DisplayOnOffObserver = 54321876;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, &PLDisplayOnOff, CFSTR("com.apple.springboard.hasBlankedScreen"), NULL, 0);
...
return YES;
}
static void PLDisplayOnOff(CFNotificationCenterRef center, void* observer, CFStringRef name, const void* object, CFDictionaryRef userInfo) {
...
DO SOME MAGIC
...
}
- (void)applicationWillTerminate:(UIApplication *)application {
...
CFNotificationCenterRemoveEveryObserver(CFNotificationCenterGetDarwinNotifyCenter(), &DisplayOnOffObserver);
...
}
Obviously you have to have the application ALWAYS running in the background (which can get tricky) or you have to only care to do it within the time that you ask for to run in the background (which isn't hard)
First step is listening to the darwin notification for the screen being toggled on/off.
Second step is implementing the callback.
Third step is stopping listening for the call back.
NOTE: DisplayOnOffObserver is a random number (not very random in my case)
3. How can you directly launch your app when the iPhone starts up?
Assuming that by directly launch, you mean launch in the background, there is actually an Apple supported way of doing this. You first have to enable Background Services for location. Second, you have to start listening for significant location changes. I don't know how well this is documented, but as soon as the iPhone boots, it tries to get it's location. When it does this, it goes from not having a location to having one (which is a significant change). Your app will launch in the background which includes calling the application:didFinishLaunchingWithOptions: method, where you can ask for more time and start other processes to permanently run in the background until the user kills your application manually. If you do permanently run in the background using this method, you do stand a chance of being rejected by Apple.
Hope any of this helps someone! If anyone needs more information, just leave a comment and I will update my answer.
When user press Home button,app don't go back the main interface or delay 5 seconds to go back the
You can't, unless you don't want your app in the appstore... The only thing you CAN do is ask for more time to save your data before your application is terminated, but the UI experience will still be the same - the iphone will go back to the main interface.
when the screen is black ,how to auto activation screen(how to catch power button press event) .
Not possible.
3. How direct launch my app when iPhone is start-up
I don't think you can do this even, with private APIs, and of course with your app not accepted in the appstore.

Crash on resuming app within 11 seconds after exit(0)

I have an app that imports data on start using Core Data. In this part of the app, I have disabled resuming (multitasking) by calling exit(0) in applicationDidEnterBackground when a flag is set. E.g.:
-(void)applicationDidEnterBackground:(UIApplication *)application {
if (allowResuming==NO){
NSLog(#"Terminating...");
exit(0);
}
}
If I then attempt to 'resume' the app (by pressing its icon) within 11 seconds of having pressed the Home button (and, therefore, exit(0) having been called), the app crashes. This doesn't happen when running through the debugger, but the crash logs suggest that it looks like the app is trying to resume the data import where it left off, which, of course, is not what I want.
Attempting to 'resume' the app again straight after this crash (i.e. within a second) is successful.
If I attempt to 'resume' the app after 11 seconds, it's fine.
I would be really grateful if anyone has any ideas and/or can point me in the right direction here.
I don't think you should be doing exit(0). To disable Multitasking, set the key UIApplicationExitsOnSuspend key in Info.plist to YES. For details, see the section Opting Out of Background Execution at
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/CoreApplication/CoreApplication.html#//apple_ref/doc/uid/TP40007072-CH3-SW1.
To discard the partial work done when the app leaves foreground, add a listener for UIApplicationWillResignActiveNotification or UIApplicationDidEnterBackgroundNotification. In the handler method, you could do something like-
[self discardPartialWorkDone];
HTH,
Akshay
You should not use exit(0) like Akshay said. In addition to that Apple will probably reject your App, because Apps which consist of code which interrupt the App like this wont be approved.

IPhone SDK Home Button

Is it possible to override the default behavior (close app) of the Home Button? And if how do you do that?
well, there's a reasonable alt to the need to detect if the Home button was tapped. i'm currently working on just such a scenario.
my app allows user input (into UITextViews). a customer has asked for an "autosave" feature where, should they (accidentally) tap the Home button during data entry, could i still capture the data entered and save it.
my testing of the sequence of viewWillDisappear in the view that is collecting the data and applicationWillTerminate show viewWillDisappear getting called before applicationWillTerminate. now i fully appreciate that this is the architected sequence Apple intended, BUT this sequence also precludes setting a simple Boolean in applicationWillTerminate to let the particular viewWillDisappear know that it is disappearing specifically due to applicationWillTerminate.
so the issue still stands. how can a UIView detect that it is disappearing specifically as a result of the app terminating?
Even if it is possible, your app will probably not be approved by Apple.
Are you planning this feature for your own private App or do you want to distribute it later on?
The home button is probably the most critical button on the device on not a good idea to change