Simulate memory warnings from the code, possible? [duplicate] - iphone

This question already has answers here:
iOS Development: How can I induce low memory warnings on device?
(10 answers)
Closed 9 years ago.
I know i can simulate a memory warning on the simulator by selecting 'Simulate Memory Warning' from the drop down menu of the iPhone Simulator. I can even make a hot key for that.
But this is not what I'd like to achieve. I'd like to do that from the code by simply, lets say doing it every 5 seconds. Is that possible?

It is pretty easy actually, however it relies on an undocumented api call, so dont ship your app with it (even if it is in a inaccessible code path). All you have to do is use [[UIApplication sharedApplication] _performMemoryWarning];.
This method will have the app's UIApplication object post the UIApplicationDidReceiveMemoryWarningNotification and call the applicationDidReceiveMemoryWarning: method on the App Delegate and all UIViewControllers.
-(IBAction) performFakeMemoryWarning {
#ifdef DEBUG_BUILD
SEL memoryWarningSel = #selector(_performMemoryWarning);
if ([[UIApplication sharedApplication] respondsToSelector:memoryWarningSel]) {
[[UIApplication sharedApplication] performSelector:memoryWarningSel];
}else {
NSLog(#"Whoops UIApplication no loger responds to -_performMemoryWarning");
}
#else
NSLog(#"Warning: performFakeMemoryWarning called on a non debug build");
#endif
}

I wrote an apple script that will hammer the simulator with memory errors, it is a bit extreme but if your code survives, then you can be more confident...
on run
repeat 100 times
tell application "System Events"
tell process "iOS Simulator"
tell menu bar 1
tell menu bar item "Hardware"
tell menu "Hardware"
click menu item "Simulate Memory Warning"
end tell
end tell
end tell
end tell
end tell
delay 0.5
end repeat
end run

Post a UIApplicationDidReceiveMemoryWarningNotification notification to the default notification center:
[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]

Just alloc-init big objects in a loop, and never release them. That should trigger a memory warning pretty quickly, I'd imagine.

Related

How to turn Auto-Lock to Never in Swift?

Is there any Swift command to actually set the Auto-Lock to Never or a specific time period? I want to create a simple app that only has two buttons: one is to set the Auto-Lock to Never and the other one is to set it back to iOS default (1 min).
So when a user open this app and tap the Never button, s/he can open other apps but the iPhone or iPad will never auto lock while running the other apps. If s/he is done with other apps, s/he can open this app again and tap the Default button to set the Auto-Lock back to 1 min.
I understand this can be done from the Settings but I am just curious how I can do it from the backend using Swift.
I am new to Swift, btw.
Thanks much!
So when a user open this app and tap the Never button, s/he can open other apps but the iPhone or iPad will never auto lock while running the other apps
You can't do that. You are sandboxed. You cannot affect what happens to the user while running some other app.
When app is open, try to disable the idleTimer in viewDidLoad
UIApplication.shared.isIdleTimerDisabled = true
When app is closed to open other apps, try to -enable again idleTimer when yourViewController disappears, so put this in viewDidDisappear
UIApplication.shared.isIdleTimerDisabled = true
You need to make use of this API call to set the idle timer disable and enable.
This is in objective-C. Just convert it to swift. The API is available in UIApplication.h
-(void) onApplicationDidActivate:(NSNotification*) notification
{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}
-(void) onApplicationWillDeactivate
{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

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;

Problem with applicationShouldTerminate on 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];
}