NSURLSession vs Background Fetch

Ok, so I watched a sample SimpleBackgroundFetch 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 am calling my application server here to get some data.

But then I saw NSURLSession docs , and it had methods like these

 – downloadTaskWithURL: 

and he said the following:

This API provides a rich set of delegation methods to support authentication and gives your application the ability to execute background loads when your application is down, or in iOS while your application is paused.

What is the difference between the two APIs? And what should I use if I want to download some data from my application server from time to time?

I simply was not sure of the difference between the two, so I just thought that I should find out my doubts. Go StackOverflow!

+6
source share
4 answers

These are completely different things.

  • Background fetch . The system starts your application after some time (heuristic), and your task is to start downloading new content for the user.

  • NSURLSession : A replacement for NSURLConnection that allows downloads to continue after the application is paused.

+9
source

The application delegate is designed to store a completion handler so that you can call it when the download is complete.

  - (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"); } 
+3
source

So, you confirm that the URL to which the delegate is vested should be called, while a normal dataTask with a block might not be like that?

0
source

NSURLSession . Allows you to download and upload in the background and pause application mode.

Background sampling : occurs according to the amount of data and the duration of the previous data transfer process. Only for 30 seconds.

0
source

Source: https://habr.com/ru/post/954849/


All Articles