Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLSession vs Background Fetch

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!

like image 441
GangstaGraham Avatar asked Sep 28 '13 18:09

GangstaGraham


3 Answers

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.

like image 185
Tricertops Avatar answered Oct 31 '22 23:10

Tricertops


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");
}
like image 29
Maximilian Litteral Avatar answered Nov 01 '22 00:11

Maximilian Litteral


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.

like image 1
ireshika piyumalie Avatar answered Oct 31 '22 23:10

ireshika piyumalie