Executing Interval output on background IOS 7 - ios

Ok , im not getting answers about this. :(
Multipeer Connectivity audio streaming stop work on background
What about this?
i'm trying to run this code on background.
- (void)applicationDidEnterBackground:(UIApplication *)application {
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSTimer *aTimer = [NSTimer timerWithTimeInterval:3
target:self
selector:#selector(showInformation)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop]
addTimer:aTimer
forMode:NSDefaultRunLoopMode];
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
Obviously i ihave this function defined on the same scope
- (void) showInformation {
NSLog(#"showInformation is called.");
}
But when i put the app on background, the interval message, stop work and when i come back to the foreground continue working ........
This means is not running on the background?.
Is this possible? or am I trying to do something stupidly impossible?
I really appreciate some help.
Thanks a lot.

Regardless your code works or not, your background task will be terminated after a while (>10 minutes) by iOS unless the UIBackgroundModes is set in your app (VOIP, Location service, Audio ..).
For more about Background Execution check Background Execution and Multitasking.
Another option in iOS7 is using Background Fetch, but you don't have control over time (there is a smart Timer used by the iOS).
For better understanding check Raywenderlich's Background Modes in iOS Tutorial.
And if you need something working check the below SO posts:
How do I get a background location update every n minutes in my iOS application?
Running iOS App in background for more than 10 minutes
Will iOS launch my app into the background if it was force-quit by the user?

Related

iOS8 : running in the background for forever : GameCenter

I know this may seem a duplicate subject but its not (hopefully its not)
We have an application that uses GameCenter in the background for backend communication, up until ios8, GameCenter has ran in the background fine.
Now I need to find a fix around this, the key is that the app needs to constantly run in the background, it uses GameCenter chat server etc, so we have enabled Audio. I can't see us being able to use VOIP as an option (Apple would probably reject it)
I tried
[self performSelectorOnMainThread:#selector(keepAlive) withObject:nil waitUntilDone:YES];
[application setKeepAliveTimeout:600 handler: ^{
[self performSelectorOnMainThread:#selector(keepAlive) withObject:nil waitUntilDone:YES];
//[[GCHelper sharedInstance] applicationWentBackground];
}];
- (void)keepAlive {
self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(#"Background handler called. Not running background tasks anymore.");
// [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
// self.bgTask = UIBackgroundTaskInvalid;
[self keepAlive];
}];
}
Which keeps it going for a bit, I guess the main question is, is it even possible now?
I have also followed this guide
http://blog.dkaminsky.info/2013/01/27/keep-your-ios-app-running-in-background-forever/
As long as the app itself is in the foreground, you can fire a notification every xx seconds which handles the background tasks.
When the full app goes into background, you only have a limited amount of time to close actions.

My iphone app background process terminates after 10 mins

I have been facing a issue that my app doesnt run background for more than 10 mins , I have implemented background task which will fetch notifications instantly.
my application background task stops after 10 mins, I have already refereed solutions of this and this , but it doesnt seem helpful
my code is as follows
-(void)methodBGTask :(UIApplication *)application{
if ([[UIDevice currentDevice] respondsToSelector:#selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//run function methodRunAfterBackground
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:#selector(methodGetNotificatioin) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
}
}
}
-(void)methodGetNotificatioin{
//retrieve notifications from service
}
Thanks In advance
This is normal. You are not supposed to run timers in the background. On iOS7 and above, you should be using background fetch mode to fetch data (or do it properly, using push).
Read here for more information on iOS7 background modes.
Note, that on iOS7 and above, background tasks are even shorter (~30 seconds) rather than 10 minutes, so you are even less encouraged to use that API for such work.
If I'm not mistaken or not misunderstanding your question, this is expected behaviour. Background tasks are time limited so that one app doesn't run indefinitely and consume resources like battery power and cellular data.
There are different types of background modes, some perform a set task and suspend when complete or timed out, others run periodically.
You're likely looking to implement background fetch, wherein the OS will periodically wake your app and allow it to check for new content and perform a quick data fetch to get the latest data from your server.
Background fetch can be triggered by a push notification that has the "content-available" flag set in its payload. The OS will be selective in scheduling background fetches for apps and will often coalesce them together to be more efficient. The OS will also learn when users run your app and try to schedule background fetches before the time a user opens your app so that the latest data is available.
You should use Push Notifications instead fetching them every 5 minutes. It's will work on the fly and will not drain the battery.

How to run location updates in background continuously in ios

UIApplication* app = [UIApplication sharedApplication];
_backgroundTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:_backgroundTask];
_backgroundTask = UIBackgroundTaskInvalid;
}];
[self startTimer];
NSLog(#"backgroundTimeRemaining: %.0f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
-(void)startTimer
{
self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:60.0
target:self
selector:#selector(repeatedMethod)
userInfo:nil
repeats:YES];
}
I'm able to run successfully when my app is in foreground but when I come to background if
backgroundTimeRemaining:10 it is running for 3 minutes but when backgroundTimeRemaining:176
it is running continuously. One thing I did not understand is why backgroundTimeRemaining is showing different numbers.How to run process continuously in Background. One thing I need to mention is my background process contains location updates. I'm very new to ios. Any help would be appreciable.
You need to set below key values in your app's info.plist file
Required background modes : App registers for location updates!
As shown in below image and implement you location manager delegate methods in AppDelegate so that its there even your app is in any view controller.
Setting the above key value in info.plist will tell ios to enable background mode for location services.
Read "Getting Location Events in the Background (iOS Only)" in:
https://developer.apple.com/library/ios/documentation/userexperience/conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html#//apple_ref/doc/uid/TP40009497-CH2-SW10
Basically your app needs to ask for permission to have a background mode for this, and use the location APIs rather than a time. You'll do some setup (get default location manager, set a delegate), call "startUpdatingLocation" from the CLLocationManager class, and then get periodic callbacks with new locations.
Keep in mind you'll drain the user's phone battery pretty fast if you do this, and Apple will reject your app from the App Store unless you give a disclaimer about this.
Set your CLLocationManager's pausesLocationUpdatesAutomatically to NO. It may help you.
For more info check Apple's Location manger documentation.

how to run process in background in ios7

I want to run my process in fore ground and background continuously.I've implemented the following code
self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
target:self
selector:#selector(repeatedMethod)
userInfo:nil
repeats:YES];
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(#"Background handler called. Not running background tasks anymore.");
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}];
In foreground it is fine but in background process is running for just 5 mins and not running more than that.But I want it to run continuously even in background also.please help.
Thats happening, because the completionHandler is called after 5 mins.You cannot run a background process for indefinite period in iOS until you use one of the UIBackgroundModes and that too is dependent upon you must provide a functionality of BackgroundMode if you use it in your application otherwise apple will reject it.
For example if you use "VoiP" BackgroundMode you application should provide "VoiP services" otherwise it will be rejected

How can I run an iOS voip app in the background without external signaling?

I'm developing a voip app for iPad. I know there are similar questions, but none of the offered solutions have worked so far. I already know that I have to set the voip flag in the info.plist file (I used xcode for that). I have also set the "application does not run in the background" to "no" (who made up that name?!?). I also configured the socket as voip using the following two lines:
CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
I read through the documentation and countless posts on SO and other forums, and there seem to be a few ways to get an app to run in the background forever. I have tried the following:
Start a long running background task, and restart the task when it fires. It was explained here on SO somewhere, but I can't find the post anymore so here is the pseudocode:
expirationHandler = ^{
if (inBackground) {
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:expirationHandler];
}
};
inBackground = true;
bgTask = UIBackgroundTaskInvalid;
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:expirationHandler];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// inform others to stop tasks, if you like
[[NSNotificationCenter defaultCenter] postNotificationName:#"MyApplicationEntersBackground" object:self];
inBackground = true;
while (inBackground) {
//send a keep alive to my server
sleep(5);
}
});
The second thing I tried was to use setKeepAliveTimeout like this:
[[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
//send a keep alive to my server
}];
The first one seems to work very well (note that battery life and app-store approval are of no concern to me), but only when the application runs from xcode. When I put the app on the device and run it without debugger, the app stays alive for about 3 minutes and then it dies.
The second one seems to be how it is supposed to be, but my problem with it is that it has a minimum time of ten minutes. My server closes the connection after ten minutes of inactivity and setKeepAliveTimeout seems to be a bit inaccurate, so sometimes it is off by half a second or so (I've experienced 2 seconds one time). This means that once every ten minutes there is a chance that my session to the server is closed.
I use a protocol called XIMSS, used by the Communigate Pro server platform. Most voip apps seem to use SIP, which can send keep alive packets from the server, but that is not a option for me. So how can I make sure my app always wakes in time to send a keep alive? Is there anything that has an interval smaller than ten minutes?

Resources