从无声远程通知中加载数据
问题描述:
我有一个应用程序在通过-[AppDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:]
处于非活动状态时接收无声推送。推送有效内容包含我需要预取的网址,以便在下次应用启动时准备好数据。从无声远程通知中加载数据
的应用程序需要调用completionHandler
当下载完成:
当下载操作完成后要执行的块。调用此块时,传入最能描述下载操作结果的提取结果值。你必须调用这个处理程序,并尽快这样做。有关可能值的列表,请参阅UIBackgroundFetchResult类型。
的问题是,我是否可以做一个简单的NSURLSession
请求,或者如果我应该做的获取使用背景的一个取as described here
选项1:使用简单NSURLSession
,并调用回调
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
NSURL *url = [NSURL URLWithString:userInfo[@"my-data-url"]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// save the result & call the
completionHandler(data ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultNoData);
}];
[task resume];
}
选项2:使用额外的背景处理用于下载内容
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
NSURLSessionDataTask *task;
__block UIBackgroundTaskIdentifier backgroundId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// time's up, cancel the download
[application endBackgroundTask:backgroundId];
backgroundId = UIBackgroundTaskInvalid;
completionHandler(UIBackgroundFetchResultFailed);
[task cancel];
}];
NSURL *url = [NSURL URLWithString:userInfo[@"my-data-url"]];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// check if time was up
if(backgroundId == UIBackgroundTaskInvalid) {
return;
}
[application endBackgroundTask:backgroundId];
backgroundId = UIBackgroundTaskInvalid;
// save the result & call the
completionHandler(data ? UIBackgroundFetchResultNewData : UIBackgroundFetchResultNoData);
}];
[task resume];
}
答
因此,要回答我的问题,一些测试后,它出现在选项2个工作得很好。我可以使用UIBackgroundTaskIdentifier
下载我需要的任何数据。如果我不使用它,下载失败
我看到有相关的内存限制同样问题的其他人:/ http://stackoverflow.com/questions/39800287/unnotificationserviceextension-memory-limit HTTPS :?//bugzilla.xamarin.com/show_bug.cgi ID = 43985 – Jan