6

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!

4

4 回答 4

10

这些是完全不同的事情。

  • 后台获取:系统在某个时间(启发式)启动您的应用程序,您的工作是开始为用户下载新内容。

  • NSURLSession:替换NSURLConnection,允许在应用程序暂停后继续下载。

于 2013-09-28T18:43:11.410 回答
3

应用程序委托用于存储完成处理程序,以便您可以在下载完成时调用它。

    - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
    NSLog(@"Handle events for background url session");

    self.backgroundSessionCompletionHandler = completionHandler;
}

并调用处理程序

- (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");
}
于 2013-09-28T18:42:21.760 回答
1

NSURLSession : 允许在应用程序的后台模式和挂起模式下上传和下载

后台提取:根据数据量和先前数据传输过程的持续时间发生。仅持续 30 秒。

于 2016-08-24T09:33:22.597 回答
0

因此,您确认应该调用具有委托的背景 URLSession ,而可能不会调用带有块的普通 dataTask ?

于 2015-10-22T08:40:45.340 回答