background task running on iphone - iphone

I have some test code which i am using to keep my app to stay running in the background state, which works quite well on the iOS 5.1 simulator but is not behaving that way on the actual device.
Now i already know the requirements i have to follow,
so i have set "background modes" to voip and location.
In my delegate's applicationDidEnterBackground method i am calling the following function
which i call "doBackgroundActivity( )"
to request time for application to complete some long running task in background :
-(void) threadedMethod{
while(true){
NSLog(#"looping");
[self showLocalNotification:#"This notification will come every 2 min. if the app is running in background. Close it!"];
[NSThread sleepForTimeInterval: (5)]; // 60 sec = 1 min
}
}
-(void) doBackgroundActivity{
self->_backgroundTask = [ [UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask: self->_backgroundTask];
self->_backgroundTask = UIBackgroundTaskInvalid;
}
];
[self threadedMethod];
[[UIApplication sharedApplication] endBackgroundTask:self->_backgroundTask];
self->_backgroundTask = UIBackgroundTaskInvalid;
}
As you see, the doBackgroundAcitivity() just calls the threadedMethod() and all that does is run an infinite loop which sends a local notification every 5 seconds or so.
Now in the simulator when i run this, and minimize the app, i see a notification every 5 seconds or so. The application keeps on running in the background even when i run other applications i see my app sending notifications.
But this is not happening on the device. It looks like that the OS kills the app just after the first notification is send and i dont see any more subsequent notifications which i expect to see later?
Is there something else i have to do to keep the application running in background ?

If all you are looking to do is present a notification to the user while your app is closed you should use UILocalNotifications.
You can set when the notification should fire, as well as whether or not it should repeat, and the amount of time between repeats.
As a side note, i wouldn't recommend using sleep() in a loop to control when code is executed like that because it stops the thread from doing anything at all, and is bad for any other tasks that would like to use that thread. Instead you should use NSTimers, and other ways of controlling the time at which code is executed.

Related

Stop setKeepAliveTimeout handler from being called after application came foreground?

For VOIP application we are sending PING packet to server every 10 minutes using setKeepAliveTimeout, everything works fine, however I'm not sure how to stop the handler from being called once application came foreground.
eg: Here is how I set the timeout
[[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ [self backgroundHandler]; }];
Background handler:
- (void)backgroundHandler
{
printf("10 minute time elapsed\n");
// do some action...
}
Above function is being called even after application came foreground, I have read in Apple documentation to set the handler nil to stop it. I have tried like below in applicationWillEnterForeground
[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:nil];
Still I'm getting call every 10 mins. How to handle this, Do I need to use flag only.
Any help is really appreciated.
you can do it like this
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
[[UIApplication sharedApplication] clearKeepAliveTimeout];
}
You have to invoke clearKeepAliveTimeout to stop the timer. setKeepAliveTimeout: is designed to keep a voip connection on and that's why it's periodically called.

How to know if a task is executing in background

In my app I'm downloading lots of images on a method.
I'm using a
downloadTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:downloadTask];
downloadTask = UIBackgroundTaskInvalid;
}];
This is working fine, if I press the home or sleep button, the images continue downloading.
I'm showing the progress in a UIProgressView inside an UIAlertView, and when the percent is 100% the alertView is dissmised and I change the viewController to other where I show the donwloaded images.
But I only want this to happen if the app is really active at the moment the download finish.
I have been looking at the app state and while it's downloading with the screen off.
[UIApplication sharedApplication].applicationState
the state is UIApplicationStateActive during all the donwload
How can I can know if the downloading is happening with the screen off or on?
EDITED AFTER ACCEPTING THE ANSWER:
I just discovered, if I tap the home button, the app enters in UIApplicationStateBackground, if I tap the wake/sleep it enters in UIApplicationStateInactive
Following the approach of the correct answer, my app contines donwloading in both cases.
The screen is off in two states (apart from when the app has not been even opened):
suspended : in this case you don't have to worry because the download won't procede until the app gets active again; It will enter this state on
background : it's in this state for a limited amount of time before going in suspend, and the screen is already off in this moment. Here you may want to check then whether to do all the things you said or not, because in this state code can be still executed. In this state the app status is UIApplicationStateBackground, so you could just perform a check like this:
You probably want to check whether the app is in background execution in order to achieve the result. Just like this:
if([[UIApplication sharedApplication] applicationState] != UIApplicationStateBackground) {
// Do stuff
}
If it's in background, so the screen is off.
UPDATE: after few test, what I figured out is that the behaviour you are expieriencing is probably due to the execution of the download on the main thread.
You should send the download on (for instance) the global queue. This way the application will enter the background state as expected:
....
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:self.bti];
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self doBackgroundStuff];
});
....
This way, if the app is put on background while the download is in progress, the application state will turn into UIApplicationStateBackground, and then you can check it as I wrote initially. If you are doing UI updates during the progress remember to send them back to the main thread (because the download is now on a different one).
You can check whether your app is running in the background or not by setting a flag in the designated application delegate methodsapplicationDidEnterBackground: and applicationWillEnterForeground:. Example:
- (void)applicationDidEnterBackground:(UIApplication *)application
_applicationRunsInForeground = NO;
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
_applicationRunsInForeground = YES;
}
If you don't want to have this _applicationRunsInForeground flag inside your application delegate, you could observe the delegate's NSNotifications in your viewcontroller class instead (UIApplicationWillEnterForegroundNotification and UIApplicationDidEnterBackgroundNotification).

Run a background thread when application enter background

I need to schedule a task in background when the application enter background state.
I have to do this in order to call a remote service each x time and then show a local notification when some event happend with the remote service.
(I know it's looks like RPN, yes it is, but for some reason I am not able to use PRM)
I tried this code :
- (void)applicationDidEnterBackground:(UIApplication *)application{
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void){
remoteServiceCallThread = [[NSThread alloc] initWithTarget:self selector:#selector(doRemoteCall:) object:nil];
[remoteServiceCallThread start];
}];
}
- (void)applicationWillEnterForeground:(UIApplication *)application{
[remoteServiceCallThread cancel];
}
I put breakpoint in the doRemoteCall selector, put is not working.
Maybe my approach is not the best one. If you have any other hack to doing this operation like I describe it I'll take it.
Thank you.
You are not starting the thread, it's initialization code is at the expiration handler block which will be called right before the app is shut down with a timeout:
A handler to be called shortly before the application’s remaining
background time reaches 0. You should use this handler to clean up and
mark the end of the background task. Failure to end the task
explicitly will result in the termination of the application. The
handler is called synchronously on the main thread, thus blocking the
application’s suspension momentarily while the application is
notified.
The task should be active for 10 minutes only (that is driven by iOS) if your app is not supporting one of the background modes (gps, audio, voip).
You also need to keep the returned UIBackgroundTaskIdentifier reference to be able to mark it as ended if the user brings the app to foreground or when task time is going to the end (that's when the handler block is called).

Force app to close and run in background

we have an app that has a specific purpose where an exit is required. After the exit a process needs to run in the background for a certain amount of time or until finished. We just need to know how to programmatically force the app to enter the background where processes can continue running. Any help on this would be great! Thanks in advance!
UPDATE: We have confirmed that there does not seem to be a programmatic way to force the app to quit / enter background and continue running background tasks. You can force the the app to exit using exit(0); but this kills the app all together. However, the bulk of this question was concerning running tasks in the background. We have found a solution that allows our app to begin processing data and handling tasks that a user has setup to be processed. Here is the code required. This needs to be added to the app delegate and multitasking is required on the device / IOS.
- (void)applicationDidEnterBackground:(UIApplication *)app{
// Check that IOS supports multitasking
if ([[UIDevice currentDevice] respondsToSelector:#selector(isMultitaskingSupported)]){
// Check that the device supports multitasking
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
// Custom setting to allow users the freedom to enable or disable background tasks
BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"backgroundTasksEnabled_key"];
if ( enabled ){
//Get the shared application instance
backGroundApp = [UIApplication sharedApplication];
background_task = [backGroundApp beginBackgroundTaskWithExpirationHandler: ^ {
[backGroundApp endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
// Run in background
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"\n\nProcess background tasks!\n\n");
// Do your work here
});
}
}
}
}
You can force an iOS app into the background by sending a registered URL to another app to handle, such as a web site URL to Safari.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: myWebsiteURL ]];
Many many apps that call Safari to handle URLs are approved by Apple.
To get any time in the background, an app has to be appropriately configured using one of the allowed background modes (audio, location or VOIP); or the app can request a few minutes of extra time in the background before being suspended by calling the beginBackgroundTaskWithExpirationHandler method
You can't have a process running (doing work) in the background in iOS, you get a few seconds when the app quits to do any clean up and that's it!
You cannot force an application into the background, I'm fairly sure that Apple's guidelines prohibit you from doing that. What could your app possibly be doing that it can only do in the background and not in the foreground?

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