我们什么时候需要使用' finishTasksAndInvalidate'对于NSUrlSession?

时间:2017-04-24 12:09:37

标签: ios nsurlsession

当我通过输入后台通知我的应用时,我会根据提到的代码调用:

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

我有以下代码段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];

来自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;

我尝试一次又一次地阅读它但却未能理解其用法。有人可以传播这个API吗?

0 个答案:

没有答案