Reputation: 1028
Is that any way to access a variable from outside a the completionHandler block? I'm developing a bandwidth speed test and need to do that. Maybe have another way so I hope you can help me.
My code:
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];
Here what I'm trying to do: when send the request and the arrive in the NStimer scheduledTimerWithTimeInterval I want to access the variable data to know exactly size and after the download over, invalidate my NStimer inside the completionHandler how I did. Thanks in advanced.
Upvotes: 0
Views: 178
Reputation: 119031
You don't have access to data
until the download is complete, so you can't use it in a timer before then. You need to rethink what you're trying to do and how you're trying to do it.
You need to use the NSURLConnection
with a delegate and the delegate methods connection:didReceiveResponse:
(which will tell you how much data to expect) and connection:didReceiveData:
(which will be called repeatedly with blocks of data).
At the start of the connection response, save the current date (this is after the server connection has been configured):
NSDate *startDate = [NSDate date];
Each time you get a block of data, you can check the size of the new data, store the total data and check the time:
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:startDate];
NSLog(@"DOWNLOAD duration %f with data size: %lu", timeInterval, [data length]);
Upvotes: 2