我希望我的 iOS 应用在后台从服务器下载一些产品信息。它应该在应用程序事件和非事件模式下工作。
使用 NSURLSessionDataTask
我可以获取数据。但无法在非事件模式下处理数据。
如果应用程序处于后台/非事件状态时我可以处理数据,您能否指导我?或任何其他建议。
请参阅下面的代码:
NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionDataTask *sessinURLResData = [session dataTaskWithURL:urlIs completionHandler:^(NSData * dataa,NSURLResponse *response,NSError * error){
responseData = dataa;// process the data and save in local DB
}];
[sessinURLResData resume];
最佳答案
至少有两种类型的后台获取:
performFetchWithCompletionHandler
中执行该提取。 .您只能执行快速(30 秒或更短)的网络请求。但是您的应用会发出网络请求,并从应用委托(delegate)调用适当的完成处理程序代码,报告失败、存在新数据或缺少新数据:- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
NSURL *url = [NSURL URLWithString:@"..."];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
completionHandler(UIBackgroundFetchResultFailed);
return;
}
BOOL foundNewData;
// parse the data; setting `foundNewData` as appropriate
if (foundNewData) {
completionHandler(UIBackgroundFetchResultNewData);
} else {
completionHandler(UIBackgroundFetchResultNoData);
}
}];
[task resume];
}
NSURLSessionConfiguration
,非常适合在后台进行大量下载/上传。为此,即使应用程序不再处于前台(即使应用程序已终止),您启动的任何下载/上传都将继续,并且当它们全部完成后,您的应用程序将在必要时重新启动,并且适当的委托(delegate)方法将是叫。但是,要做到这一点,您必须:[NSURLSessionConfiguration backgroundSessionConfiguration:identifier]
; NSURLSession
(你是); handleEventsForBackgroundURLSession
,捕获 completionHandler
;和 URLSessionDidFinishEventsForBackgroundURLSession:
在 session 委托(delegate)中,它将调用 completionHandler
当您处理完所有内容后。 做后台请求还有其他技术,但这是两个主要的 iOS7 特定的后台网络。您没有告诉我们您使用的是哪一个,也没有向我们展示足够的代码来诊断出了什么问题。
关于ios - NSURLSession 数据任务 - 处理检索到的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855984/