When do we need to use "finishTasksAndInvalidate" for NSUrlSession?

I call the specified code when my application is notified by entering in the background:

[[NSNotificationCenter defaultCenter] addObserver: self
                            selector: @selector(handleDidEnterBackground)
                            name: UIApplicationDidEnterBackgroundNotification
                            object: nil];

I have the following code snippet handleDidEnterBackground:

NSURLSession *session;

// ...

sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.my.company"];
sessionConfiguration.allowsCellularAccess = YES;
sessionConfiguration.sessionSendsLaunchEvents = NO;
session = [NSURLSession sessionWithConfiguration:sessionConfiguration 
            delegate:self 
       delegateQueue:nil];


NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request];
    [task resume];
 // why do I need this line?   
[session finishTasksAndInvalidate];

From the Doc:

/* -finishTasksAndInvalidate returns immediately and existing tasks will be allowed  
* to run to completion.  New tasks may not be created.  The session  
* will continue to make delegate callbacks until URLSession:didBecomeInvalidWithError:  
* has been issued.   
*
* -finishTasksAndInvalidate and -invalidateAndCancel do not  
* have any effect on the shared session singleton.  
*  
* When invalidating a background session, it is not safe to create another background  
* session with the same identifier until URLSession:didBecomeInvalidWithError: has  
* been issued.
  */
- (void)finishTasksAndInvalidate;

I try to read it again and again, but do not understand its use. Can anyone extend the light to this API?

+4
source share

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


All Articles