我有一个应用程序,当它通过 -[AppDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] 处于非事件状态时接收静默推送。推送负载包含一个我需要预取的 url,以便在下次应用启动时准备好数据。
下载完成后应用需要调用completionHandler :
The block to execute when the download operation is complete. When calling this block, pass in the fetch result value that best describes the results of your download operation. You must call this handler and should do so as soon as possible. For a list of possible values, see the UIBackgroundFetchResult type.
问题是我是否可以做一个简单的 NSURLSession 请求,或者我是否应该使用后台提取 as described here 之一进行提取
选项1:使用简单的NSURLSession 并调用回调
- (void)applicationUIApplication *)application didReceiveRemoteNotificationNSDictionary *)userInfo fetchCompletionHandlervoid (^)(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)applicationUIApplication *)application didReceiveRemoteNotificationNSDictionary *)userInfo fetchCompletionHandlervoid (^)(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];
}
Best Answer-推荐答案 strong>
所以回答我自己的问题,经过一些测试,看来 选项 2 工作得很好。我可以使用 UIBackgroundTaskIdentifier 下载我需要的任何数据。如果我不使用它,下载失败
关于ios - 从静默远程通知加载数据,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/42534582/
|