Ok, so I was looking at the SimpleBackgroundFetch example project, and it uses the following in the App Delegate:
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:someTimeInSeconds];
//^this code is in didFinishLaunchingWithOptions
-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
//do something + call completionHandler depending on new data / no data / fail
}
So, basically I assume, that I call my app's server here, to get some data.
But then I saw the NSURLSession docs, and it had methods like these
– downloadTaskWithURL:
and it said the following:
This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended.
So what's the difference between these two APIs? And what should I use if I want to download some data from my app's server every now and again?
I just wasn't sure about the difference between the two, so I just thought I should get my doubts clarified here. Go StackOverflow!
These are completely different things.
Background Fetch: System launches your app at some time (heuristics) and your job is to start downloading new content for user.
NSURLSession: Replacement for NSURLConnection, that allows the downloads to continue after the app is suspended.
The application delegate is for storing the completion handler so you can call it when your download is finished.
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
NSLog(@"Handle events for background url session");
self.backgroundSessionCompletionHandler = completionHandler;
}
and call the handler
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
WebAppDelegate *appDelegate = (WebAppDelegate *)[[UIApplication sharedApplication] delegate];
if (appDelegate.backgroundSessionCompletionHandler) {
void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
appDelegate.backgroundSessionCompletionHandler = nil;
completionHandler();
}
NSLog(@"All tasks are finished");
}
NSURLSession:Allows to uploading and downloading in the background mode and suspend mode of application
Background Fetch:Happens according to volume of the data and duration of previous data transferring process.Only last for 30s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With