Problem with applicationShouldTerminate on iPhone - iphone

I'm having a problem with applicationShouldTerminate.
What ever I do it seams that has no effect. Any help would be
appreciated.
I'm well versed in programing but this just gives me headache. Im going
over some basic tutorials for xcode , as I'm new to mac in general, and am currently looking at a simple flashlight app.
It exists but I would like to add a alert box here with option not to
quit.
(void)applicationWillTerminate:(UIApplication *)application
{
[application setIdleTimerDisabled:NO];
}
this has no effect, alert is closed even before its created.
(void)applicationWillTerminate:(UIApplication *)application
{
[application setIdleTimerDisabled:NO];
UIAlertView *alertTest = [[UIAlertView alloc]
initWithTitle:#"This is a Test"
message:#"This is the message contained
with a UIAlertView"
delegate:self
cancelButtonTitle:#"Button #1"
otherButtonTitles:nil];
[alertTest addButtonWithTitle:#"Button #2"];
[alertTest show];
[alertTest autorelease];
NSLog(#"Termination");
}
I did some reading online and found that it should be possible to do
this with
(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender
But no mater where I put that declaration I get error: syntax error
before NSApplicationTerminateReply.
There is no syntax error except that xcode seems not to recognize
NSApplicationTerminateReply as valid input.
Any sample code would be greatly appreciated.

I know this is a non-answer, but hopefully I can be helpful:
Displaying a "Really quit?"-type alert like this, even if you can pull it off technically (and I'm not sure you can), is a bad idea and is likely to either cause rejection from the App Store or, at best, an inconsistent user experience because no other apps do this.
The convention with iPhone apps is to save state if necessary, then yield control (for termination) as quickly as possible when the user hits the home button or switches apps.
To ensure a consistent experience, Apple probably has an aggressive timer in place to restrict what you can do in applicationWillTerminate. And even if they don't have a technical measure in place, they probably have an App Store approval policy to ensure that applications quit immediately when they're asked to.

applicationShouldTerminate and NSApplication do not exist on the iPhone. You have to use UIApplication.
The alert view is never shown because the 'show' method does not block, and therefore, the end of 'applicationWillTerminate' is reached immediately after you create the alert view and try to show it. I believe this is by design. You can't really begin asynchronous operations in 'applicationWillTerminate'.

With regards to the applicationShouldTerminate error, in case anyone's curious, NSApplicationTerminateReply and NSApplication seem to be deprecated...even though the OP's method is exactly how it appears in the docs!
Defining your method as the below should build with no errors:
-(BOOL)applicationShouldTerminate :(UIApplication *)application

I think I found the answer to what I wanted to do but will need to check it when I get back home.
Some directions were found here
http://blog.minus-zero.org/
The iPhone 2.0 software was recently released, and with it came the
ability for users to download native apps (i.e., not web sites)
directly to their phones from within the iPhone UI or via iTunes.
Developers (anyone who pays Apple 59GBP for the privilege) can then
write their own apps and have them available for purchase in the App
Store.
One limitation of the Apple-sanctioned SDK is that only one
application is allowed to be running at a time. This presents a
problem for apps such as IM clients, music players and other programs
whose functionality relies on being able to run in the background.
Another example (courtesy of James) would be an app that takes
advantage of the iPhone 3G's GPS chip to create a log of all the
places you visit.
However, there is a neat trick that I discovered: your app will only
get terminated if you switch away from it, and hitting the iPhone's
power button while your app is in the foreground doesn't count as
switching away. The upshot of this is you can create apps which
continue to run while the iPhone is in your pocket - perfect for the
GPS example.
Achieving this is as simple as implementing two methods in your
UIApplication delegate - applicationWillResignActive: and
applicationDidBecomeActive:. Here's a simple example to demonstrate
the effect.
In your UIApplication delegate header file, add a new ivar: BOOL
activeApp. Then, in your implementation, add the following three
methods:
- (void)applicationWillResignActive:(UIApplication *)application {
NSLog(#"resigning active status...");
activeApp = NO;
[self performSelector:#selector(sayHello) withObject:nil afterDelay:1.0];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(#"becoming the active app...");
activeApp = YES;
}
- (void)sayHello {
NSLog(#"Hello!");
if (!activeApp)
[self performSelector:#selector(sayHello) withObject:nil afterDelay:1.0];
}

Related

App Rejected for failing to launch? ...and others

My game was just rejected from the AppStore for the following two reasons...
We found that your app failed to launch on iPhone 4 running iOS 5.1,
on both Wi-Fi and cellular networks.
We encountered the issue when selecting the application on the Home
screen - the app displayed a launch image then quit unexpectedly
And
Your app did not run at iPhone resolution and/or 2x iPhone 3GS resolution when reviewed on iPad.
Both of these confuse me, I currently do not have Lion installed so cannot test in 5.1 but, it works just fine in 5.0.1 and below.
Also, I have been testing on only my iPad, have no iphone to test on, but the game and graphics run just fine on the iPad. Though! I only have graphic files labeled #2x.png, and none with out it. Could that be the problem here?
If anyone has any advice that would be awesome, I responded to apple's rejection, but i bet it takes a while for them to get back to you, and i'd really like to move this along. Thanks!
**Updated
My didFinishLaunchingWithOptions:
Is as follows
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
mainMenu = [[MainMenu alloc] init];
self.navController = [[UINavigationController alloc] initWithRootViewController:mainMenu];
self.navController.navigationBar.hidden = YES;
[self.window addSubview:navController.view];
[self.window makeKeyAndVisible];
[[GCHelper sharedInstance] authenticateLocalUser];
if ([[[NSUserDefaults standardUserDefaults] objectForKey:#"missingWordsAdded"] intValue] != 1) {
[self forceAddWords];
}
if (![[NSUserDefaults standardUserDefaults] objectForKey:#"EnableSoundEffects"]){
[[NSUserDefaults standardUserDefaults] setObject:#"YES" forKey:#"EnableSoundEffects"];
}
return YES;
}
GCHelper sets up GameCenter. thanks!
I've got a few suggestions:
Do a reset on your simulator, launch your program and see if it works
Uninstall your app from iPad, run it from Xcode and see if it works
Ask a friend to test an ad-hoc copy, or attach to your Xcode and run debug copy
Depending on your implementation, you should do some blind check on your startup code (didFinishLaunchingWithOptions or singleton instances). Especially those area that involves GCD, #synchronize, access on NSArray or NSDictionary. And things like default preference initializing and database creation are likely to produce this kind of problem.
Regarding the review process, my log indicates that Apple staff at Cupertino uses an iPad 2 with WiFi connection to run your app. They are not toying with you if they say they can't run your app.
1) "app failed to launch" for different configurations of phone and iOS is a big issue to reproduce because you may not have all the phones with different iOS versions at hand. You can try https://testflightapp.com/ for example, and can come to know your app performance with different configurations.
my app is also rejected for same reason. here u have first check the internet connectivity where it will needed than u have do your code.
to check internate connectivity u can use reachability classes.

Quit the application in iphone by code [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
how to quit (exit) an app in iPhone4 sdk
I have a close button in the first view of the app. I need to close the application succesfully on button click. I had tried the two cases but not worked.
[[UIApplication sharedApplication] terminate];
[[UIApplication sharedApplication] exit(0)];
iOS apps aren't supposed to quit on their own; the user quits/suspends apps using the devices' button. For more on this read Don't Quit Programmatically in the iOS Human Interface Guidelines.
If your app has finished whatever task it's meant to do and you would normally exit, you can instead just reset the app's state back to whatever it would be when the app starts. You should probably include some cues in the UI so that the user understands what's happening -- remember, the user is supposed to be in charge here. But if your app has reached it's logical conclusion, it may be that the thing that will feel most "right" to the user will be to go back to the initial state. You often see this with games -- once the game is done, the app goes back to the intro screen and waits for the user to start another game.
Note that both snippets you posted are incorrect. UIApplication doesn't have a -terminate method. (NSApplication does have a -terminate: method, but it takes a parameter and obviously isn't available in iOS.) Your second example mixes function call syntax with message sending syntax in a way that doesn't make any sense -- I doubt that will even compile.
Similar Thing i am also doing while i want to Quit my application after Show alert i think this may help u...
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
NSLog(#"%#",alertView.title);
if(alertView.title== #"Collision failed")
{
if(buttonIndex==0)
{
//gameState = kGameStateRunning;
[self loadView];
[self viewDidLoad];
count=0;
}
else
{
exit(0);
}
}
else
{
if(buttonIndex==0)
{
//gameState = kGameStateRunning;
[self loadView];
[self viewDidLoad];
}
else
{
second_stage *obj=[[second_stage alloc]initWithNibName:#"second_stage" bundle:nil];
obj.count2=count;
[self presentModalViewController:obj animated:YES];
}
}
simply i am writing exit(0);
Just call exit(0);
No need to call with the instance of UIApplication. But before call the exit method, do whatever you need to do such as saving the state, values if any, etc.,
I am not very sure but acc to HIG, iPhone apps should not be closed.
but you can Set UIApplicationExitsOnSuspend in your application's plist.When you switch to another app, it will cause the app not to go into the background under iOS4. :)

applicationWillTerminate when is it called and when not

Hi I have read several questions on SO about applicationWillTerminate getting called and not getting called.
I wanted to summarize what I understood as there are several posts that speak differently.
For IOS (without multitasking) it is called always when home button is pressed.
For IOS 4 and above
a. it is not called when pressing home button (as the app moves to background)
b. it is called when closing the app from the multi tasking dock and if the app has a sudden terminate flag in info.plist disabled else it is not called. ( I set the "Application should get App Died events" and even then on closing the app from the multitasking dock the terminate function did not get called)
Based on that I had a couple of questions
Is it a good practise to set the Application should get App Died events flag? ( I set the "Application should get App Died events" and even then on closing the app from the multitasking dock the terminate function did not get called)
or
Is registering for "UIApplicationWillTerminateNotification" a better thing to do than the info.plist setting?
Basically I need to do some work only when the app terminates and NOT when it moves to background.
or
EDIT (1):
When the app is terminated the following is sent to the APP. How do I catch it?
Program received signal: “SIGKILL”.
EDIT (2):
Please note : It is not getting called in IOS 4 and above when removing from the multitasking dock. You might think it is. But in my case it is not.
I am asking if anyone knows why? Is there something else I am missing.
Also Note I set the "Application should get App Died events" and even then it is not getting called.
EDIT (3):
The answer for the following question also did not work.
applicationWillTerminate does not get invoked
Anybody facing the similar issue as me?
In short, unless you have UIApplicationExitsOnSuspend in your Info.plist set to YES, in iOS4 and above there is no guarantee that applicationWillTerminate: will ever get called.
As the documentation says:
For applications that support background execution, this method is
generally not called when the user quits the application because the
application simply moves to the background in that case. However, this
method may be called in situations where the application is running in
the background (not suspended) and the system needs to terminate it
for some reason
(Emphasis mine.)
If you need to do something before the app exits you need to do it in applicationDidEnterBackground:. There is no way to catch SIGKILL.
I see -applicationWillTerminate: getting called with the following test. In a new project (I used the 'Single View Application' template), add the following to the AppDelegate:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(#"%s", __PRETTY_FUNCTION__);
__block UIBackgroundTaskIdentifier identifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
if (identifier != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:identifier];
identifier = UIBackgroundTaskInvalid;
}
}];
dispatch_async(dispatch_get_main_queue(), ^{
for (int i=0; i < 20; i++) {
NSLog(#"%d", i);
sleep(1);
}
if (identifier != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:identifier];
identifier = UIBackgroundTaskInvalid;
}
});
}
- (void)applicationWillTerminate:(UIApplication *)application
{
NSLog(#"%s", __PRETTY_FUNCTION__);
}
This example will start a background task when the app enters the background. The task is just a 20s delay (with logging once a second) that keeps the app running in the background (note the difference between running in the background and suspended) long enough to allow it to be killed from the app switcher.
So, to test it, run the app, hit the home button to send the app to the background, then before the 20s delay is up, remove the app from the app switcher. After the end of the 20s, -applicationWillTerminate: is called. You can watch the console in Xcode to verify that this is the case.
I tried this in the iOS Simulator for iOS 5.1 and 6.1 (both iPhone) and saw it happen in both cases. I also tested on iPhone 4S running iOS 6.1.2 and saw the same behavior.
As I know, there are 3 situations that your application will die.
Terminated by the end user, you can do something in -[UIApplication applicationWillEnterBackground:], in which case, -[UIApplication applicationWillTerminate:] will NOT be called.
Dropped by the system, such as memory not enough, you can do something in -[UIApplication applicationWillTerminate:], in which case, we do NOT know whether applicationWillEnterBackground: has been called;
Crashed, nothing can be done except using some kind of Crash Reporting Tool. (Edited: catching SIGKILL is impossible)
Source: http://www.cocos2d-iphone.org/forum/topic/7386
I copied my state saving code from applicationWillTerminate to applicationDidEnterBackground and also added a multitaskingEnabled boolean so that I only call state saving in applicationDidEnterBackground. BECAUSE, there is one instance on a multitasking device where applicationWillTerminate is called: If the app is in the foreground and you power off the device. In that case, both applicationDidEnterBackground and applicationWillTerminate get called.
As we know that the App has only 5 sec when -applicationWillTerminate being called. So If someone want to update the server at that point. Than use
Synchronous call.
[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&error];
Note:- -applicationWillTerminate will not call if app is being killed from suspended state. Suspended state means app is not working anything in backgroupd. One of the solution for this is to use background task.
Based on Andrew's test, I understand the docs for applicationWillTerminate(_:) to be meant as having the following clarifications:
For apps that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the app. For apps that support background execution, this method is generally not called [right away] when the user quits the app because the app simply moves to the background in that case. However, this method may be called [instead of beginBackgroundTask(expirationHandler:)] in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.
// absolute answer applicationWillTerminate
func applicationWillTerminate(application: UIApplication) {
print("applicatoinWillTerminate")
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
step 1: command + shift + h (double click(tab))
step 2: move app top side (kill)
step 3: applicationWillTerminate Work

Location services don't stop when application is terminated

I'm currently developing an iPhone application which needs location services for various use including AR.
I test everything on simulator and on my iPhone 3GS and everything went well.
I recently tested on iPhone4 and on iPad2 and the location service (the little icon in status bar) keeps displaying even when I manually kill the app!
The only way to disable this icon is to manually stop the location service for my app in the settings.
Does anyone know something about this?
If needed I can post my code.
Thank you in advance
Edit :
When I kill the application, go to location services, switch off my app the location icon disappears. But when I switch it back on, it reappears! Is that normal?
I've found the answer! It came from region monitoring, which I enabled before, but removed all code using it weeks ago.
As I had already tested on the iPad, and even if I deleted and re-installed the app, the system seems to have kept information on region I monitored.
Thus, as described by the documentation, the iOS kept on locating for my App, just as startMonitoringSignificantLocationChanges.
Thanks for you answers, it gave me a better understanding of the location system and how to efficiently use it (in particular thanks to progrmr and Bill Brasky)
Sounds like you're app is going into the background and still using CLLocation. You can stop CLLOcationManager when you receive notification that you're app is resigning active, that's the best way. Then resume when it becomes active. The answer in this question show how to do that here
[EDIT] When your app goes into the background or resigns active for any reason (ie: phone call) you should stop location services at that time. You need to subscribe to the notifications and provide a method to stop and start location services, something like this:
-(void)appDidBecomeActiveNotif:(NSNotification*)notif
{
[locationManager startUpdatingLocation];
}
-(void)appWillResignActiveNotif:(NSNotification*)notif
{
[locationManager stopUpdatingLocation];
}
-(void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(appDidBecomeActiveNotif:) name:UIApplicationDidBecomeActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(appWillResignActiveNotif:) name:UIApplicationWillResignActiveNotification object:nil];
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
I ran into this same exact issue when using the region monitoring tools. It didn't matter what I did to disable the regions, the arrow remained. I did finally solve the issue by cleaning up the calls to locationManager. If you are closing your view and don't need the location manager, set it to nil and/or release it. If you are monitoring location in the background, it will stay up there, but if not, make sure you are cleaning up all your location monitoring.
It seems like it is a bug, but as I found out, it is not. Just requires a bit more cleanup.
I have been battling with this problem for a while, and I think I've finally gotten to the bottom of it..
The reason that the location service doesn't stop when you ask it to is not because you haven't stopped it or released it properly. It's actually caused by releasing and re-allocating the CLLocationManager itself, in my experience.
If you have code which releases your CLLocationManager in applicationDidEnterBackground, and then you allocate a brand new one in applicationDidEnterForeground, etc., then you'll probably have this problem.
The solution is this:
Only create your CLLocationManager object once, in applicationDidFinishLaunching.
To start, call startUpdatingLocation, startMonitoringSignificantLocationChanges etc. as normal.
To stop updates, call the appropriate stopUpdatingLocation, stopMonitoringSignificantLocationChanges etc. as normal.
Never, ever release your CLLocationManager or set its' reference to nil (except possibly in applicationWillTerminate, but that probably won't make any difference).
This way, I went from having my app continue to use location services for up to 12 hours after putting my app away in the background, to the location services arrow disappearing within 10 seconds of backgrounding with this new approach.
Note: Tested on iPhone 4S running iOS 5.1.1. To get accurate results on your app's performance in this regard, make sure you go into Settings->Location Services->System Services and turn off the Status Bar Icon switch. That way, the status bar arrow will accurately reflect usage by apps alone.
Presumably this is so users don't need to stare at the bar to notice some mischievous app is using location services. That icon appears when you use any location services and remains for some indeterminate time afterwards.
This is intentional behavior Apple wants users to know which apps are using their locations. It seems this is sensitive data, wouldn't you agree?
This is the solution which fixed this problem for me.
Just stop monitering location changes in
- (void) applicationDidEnterBackground: (UIApplication *)application
{
[locationManager stopMonitoringSignificantLocationChanges];
locationManager.delegate = nil;
}
not in applicationWillEnterForeground: .Still,it takes a few seconds to disappear locating icon.
I don't know why it isn't working in the latter method.
I've run into that problem a while ago and found it useful to apply only one method of applicationDelegate object
- (void)applicationWillEnterForeground:(UIApplication *)application;
If you'll stop your CLLocationManager from receiving updates inside that call, you'll be alright. Of course you'll need to start updating somewhere else, and - (void)applicationDidBecomeActive:(UIApplication *)application; will be a good choice. Also you need to note, that there are two methods of location awareness
the gps based -(void)start/stop_UpdatingLocation;
and the 3g/wi-fi based -(void)start/stop_MonitoringSignificantLocationChanges;

Awake from sleep event on the iPhone?

Is there any way to detect if the iPhone wakes up from sleep while you're app is running? Eg: your app is running, the user locks the screen (or the screen auto locks) and some time later the user unlocks the screen and up pops your app. Is there some way to get an event at that point or detect it somehow?
I've tried searching the Google and this forum, but I can't seem to find anything about it.
See applicationDidBecomeActive: on UIApplicationDelegate.
Stick these in you AppDelegate.m file:
-(void) applicationWillResignActive:(UIApplication *)application {
NSLog(#"Asleep");
}
-(void) applicationDidBecomeActive:(UIApplication *)application {
NSLog(#"Awake");
}
#Kevin - Nothing wrong with your answer - thanks by the way. Just thought I'd save the next person a Google search.