beginBackgroundTaskWithExpirationHandler - iphone

I am making an application where audio will play in the background. In the following code, bgTask is undeclared. What kind of object should bgTask be?
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{});
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}

You need to declare bgTask before you assign:
UIBackgroundTaskIdentifier bgTask = 0;

I cannot comment on previous answers, however to initialize UIBackgroundTaskIdentifier you should not set it to nil or 0. You should set it to:
UIBackgroundTaskInvalid
In the documentation UIBackgroundTaskInvalid says it should be used to initialize variables or to check for errors.

You are using the bgTask in the block so you have to declare it like this..
__block UIBackgroundTaskIdentifier bgTask = 0;
__block will allow this variable to use in the block method. And its have double underscore.

Related

periodically download file from server and notify the app

Again I have a similar doubt as specified in the link setKeepAliveTimeout and BackgroundTasks.
I have to periodically take a file from server and accordingly provide local notification.
This has to be done when app is in background state.
Create backgoud task in your interface:
#property (nonatomic) UIBackgroundTaskIdentifier bgTask;
Than create method to backgroud working:
- (void) backgroundMethod {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//create backgriund task;
self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask: self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
}];
//do your stuff;
[[UIApplication sharedApplication] endBackgroundTask: self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
});
}
And call it whenewer you want periodicaly.

How to increase applicationDidEnterBackground in iPhone?

I call one api in applicationDidEnterBackground, but applicationDidEnterBackground method returns after 5 seconds so how could I increase timer or after api finish then only applicationDidEnterBackground will return all of us suggest use beginBackgroundTaskWithExpirationHandler
But I don't know how to use it can anyone guide me?
Here is my code
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSString *link=[NSString stringWithFormat:#"http://www.askpundit.com/dev/js_chat/getNewRequest.php?updateStatus=%#&clientid=%#",UpdateStatus,[self getSetting:#"Clientid"]];
NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:link]];
NSURLConnection *connaction=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connaction)
{
responsedata=[NSMutableData data];
NSLog( #"Data Saved");
}
}
Can any one guide me how return applicationDidEnterBackground after my call finish.
As you surmise, beginBackgroundTaskWithExpirationHandler is what you should use. It's very straightforward. This snippet is minimally proofread, and incomplete - but demonstrates the approach.
- (void)applicationDidEnterBackground:(UIApplication *)application {
_completionTask = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:_completionTask];
_completionTask = UIBackgroundTaskInvalid;
}];
// begin your NSURLConnection, etc.
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if( _completionTask != UIBackgroundTaskInvalid ) {
[application endBackgroundTask:_completionTask];
_completionTask = UIBackgroundTaskInvalid;
}

iOS HTTP request while in background

It is possible to make HTTP async requests to PHP server while the app being in background?
The app is a location based one, and should gather current location and send the coordinates to server every 5(or other value) minutes. Can I make the http posts to the server even the app is in background? I read lot of thoughts about this, but some of them told that can be done, others that can't be done.
Thanks,
Alex.
It can be done but it is unreliable because you ask the OS for time to send something and it can accept or deny your request. This is what I have (stolen from somewhere on SO):
[...] //we get the new location from CLLocationManager somewhere here
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
if (isInBackground)
{
[self sendBackgroundLocationToServer:newLocation];
}
- (void) sendBackgroundLocationToServer: (CLLocation *) lc
{
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
[dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.latitude] forKey:#"floLatitude"];
[dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.longitude] forKey:#"floLongitude"];
// send to server with a synchronous request
// AFTER ALL THE UPDATES, close the task
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}
}
These links will help you out...
iphone - Connecting to server in background

Location Background - Network Connection

I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here
- (void)applicationDidEnterBackgroundUIApplication *)application
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
[locationManager startUpdatingLocation];
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do the work associated with the task
// code for Posting Data Here
NSLog(#"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
- (void)locationManagerCLLocationManager *)manager
didUpdateToLocationCLLocation *)newLocation
fromLocationCLLocation *)oldLocation
{
NSLog(#"Location Change");
}
This Method Call Only Once.
Of course, and you should be happy what delegate received message at least once. There is no code which will delay application suspending in your background execution code. Also this kind of code can work about 10 minutes and will be killed by system.
If you need to track user location in background, than maybe you just set this mode for application background operation in Info.plist (UIBackgroundModes and add option location) and your app won't be suspended (only in case of heavy memory usage)

Location Background - Network Connection

I am trying to post data on background and I want to receive response from in regular interval that so that I am trying to use CLLocation Manager . But didUpdateToLocation method calling only once.
Please suggest me !
enter code here
- (void)applicationDidEnterBackgroundUIApplication *)application
{
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone; // whenever we move
locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 100 m
[locationManager startUpdatingLocation];
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_ QUEUE_PRIORITY_DEFAULT, 0), ^{
//Do the work associated with the task
// code for Posting Data Here
NSLog(#"backgroundTimeRemaining: %f", [[UIApplication sharedApplication] backgroundTimeRemaining]);
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
- (void)locationManagerCLLocationManager *)manager
didUpdateToLocationCLLocation *)newLocation
fromLocationCLLocation *)oldLocation
{
NSLog(#"Location Change");
}
This Method Call Only Once.
Make sure you are not testing this in simulator.
You don't get location updates on the iphone simulator.
In order to run location services in the background, you need to modify your plist such that the UIBackgroundModes key contains location.
the call should be
[locationManager startMonitoringSignificantLocationChanges];