为什么我们在这里使用ephemeralSessionConfiguration?

时间:2015-11-04 18:01:21

标签: ios nsurlsession

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    if (self.photoDatabaseContext) {
        NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        sessionConfig.allowsCellularAccess = NO;
        sessionConfig.timeoutIntervalForRequest = BACKGROUND_FLICKR_FETCH_TIMEOUT;
        NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[FlickrFetcher URLforRecentGeoreferencedPhotos]];
        NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request
                                                        completionHandler:^(NSURL *localFile, NSURLResponse *response, NSError *error) {
                                                            if (error) {
                                                                NSLog(@"Flickr background fetch failed: %@", error.localizedDescription);
                                                                completionHandler(UIBackgroundFetchResultNoData);
                                                            } else {
                                                                [self loadFlickrPhotosFromLocalURL:localFile
                                                                                       intoContext:self.photoDatabaseContext
                                                                               andThenExecuteBlock:^{
                                                                                   completionHandler(UIBackgroundFetchResultNewData);
                                                                               }
                                                                 ];
                                                            }
                                                        }];
        [task resume];
    } else {
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

似乎合乎逻辑的是,必须有backgroundSessionConfigurationWithIdentifier而不是ephemeralSessionConfiguration,因为它是在后台加载的。但来自斯坦福iOS课程的Paul Hegarty说第二个更好。为什么?他说了一些关于离散取物的事情,但我不明白。

1 个答案:

答案 0 :(得分:1)

ephemeralSessionConfiguration :与默认配置类似,但所有与会话相关的数据都存储在内存中。将此视为“私人”会话。 backgroundSessionConfiguration :允许会话在后台执行上载或下载任务。即使应用程序本身被暂停或终止,转移也会继续。 更多信息:https://www.raywenderlich.com/110458/nsurlsession-tutorial-getting-started