有没有办法从completionHandler块中访问变量?

时间:2014-03-19 22:35:31

标签: ios objective-c asynchronous download

是否有任何方法可以从completionHandler块外部访问变量?我正在开发带宽速度测试并且需要这样做。也许有另一种方式,所以我希望你能帮助我。

我的代码:

NSTimer *myTimer;


[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error)
     {
         NSTimeInterval timeInterval = [start timeIntervalSinceNow];
         NSLog(@"DOWNLOAD COMPLETED IN %f", timeInterval );
         [myTimer invalidate];
     }];

myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                               target:self
                                             selector:@selector(count:)
                                             userInfo:data //variable from completionHandlerBlock
                                              repeats:YES];

这就是我要做的事情:当发送请求并到达NStimer scheduledTimerWithTimeInterval时,我想访问变量数据以确切知道大小并在下载完毕后,在completionHandler中使我的NStimer无效我怎么样没有。谢谢你提前。

1 个答案:

答案 0 :(得分:2)

在下载完成之前,您无法访问data,因此在此之前您无法在计时器中使用它。您需要重新考虑您尝试做的事情以及您尝试做的事情。

您需要将NSURLConnection与委托和委托方法connection:didReceiveResponse:(将告诉您预期会有多少数据)和connection:didReceiveData:(将使用块重复调用)一起使用数据)。

在连接响应开始时,保存当前日期(这是在配置服务器连接之后):

NSDate *startDate = [NSDate date];

每次获得一个数据块,您都可以检查新数据的大小,存储总数据并检查时间:

 NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:startDate];

 NSLog(@"DOWNLOAD duration %f with data size: %lu", timeInterval, [data length]);