【发布时间】:2012-03-11 22:14:59
【问题描述】:
我正在尝试在这里关注之前的帖子:Best practice to send a lot of data in background on iOS4 device?
基本上,我有一个名为 getRequest 的方法,它可以从 Web 服务器获取信息。我需要来自 Web 服务器的大约 50 条数据。所以同时,我有 50 个委托调用 connectionDidFinishLoading。目前我的 getRequest 看起来像:
-(void) getRequestWithURL:(NSString *) requestURL
{
static int getRequest = 0;
NSLog(@"getRequest: %i", getRequest);
getRequest++;
UIApplication *app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier taskID;
taskID = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"Time remaining: %f", app.backgroundTimeRemaining);
NSLog(@"Background task not completed");
[app endBackgroundTask:taskID];
}];
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:requestURL]];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self] ;
[self startRequestWithConnection:con];
[req release];
if (taskID == UIBackgroundTaskInvalid) {
NSLog(@"Failed to create background task identifier");
}
}
然后在我的connectionDidFinishLoading中:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// process data from server
// endBackgroundTask:someTaskID???
}
我知道您可以多次调用 beginBackgroundTaskWithExpirationHandler,但我不知道我在 getRequest 方法中所做的是否正在这样做,因为每次调用该方法时我只有一个变量 __block UIBackgroundTaskIdentifier taskID。而且我也不确定是否需要在每次调用 getRequest 时在 connectionDidFinishLoading 方法中调用 endBackgroundTask,因为您应该平衡 beginBackgroundTaskWithExpirationHandler 与 endBackgroundTask: 调用。如果是这样,我该怎么做,因为我的 getRequest 目前没有那个基础设施?我是否需要 50 个 ivars 才能让 connectionDidFinishLoading 方法看到对 getRequest 的 50 个初始调用?谢谢。
【问题讨论】:
-
这里的任务是什么? backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ [[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID]; backgroundTaskID = UIBackgroundTaskInvalid; }];这只是返回一个背景 ID,但实际的方法调用在哪里?
标签: iphone