Im making an app where one of the features I want to offers is to measure de download speed of the connection. To get this I`m using NSURLConnection to start the download of a large file, and after some time cancel the download and make the calculation (Data downloaded / time elapsed). While other apps like speedtest.net give a constant speed every time, mine fluctuates 2-3 Mbps more or less.
Basically what I`m doing is, start the timer when the method connection:didReceiveResponse: is called. After 500 call of the method connection:didReceiveData: I cancel the download, stop the timer and calculate the speed.
Here is the code:
- (IBAction)startSpeedTest:(id)sender
{
limit = 0;
NSURLRequest *testRequest = [NSURLRequest requestWithURL:self.selectedServer cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
NSURLConnection *testConnection = [NSURLConnection connectionWithRequest:testRequest delegate:self];
if(testConnection) {
self.downloadData = [[NSMutableData alloc] init];
} else {
NSLog(@"Failled to connect");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.startTime = [NSDate date];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.downloadData appendData:data];
if (limit++ == 500) {
[self.connection cancel];
NSDate *stop = [NSDate date];
[self calculateSpeedWithTime:[stop timeIntervalSinceDate:self.startTime]];
self.connection = nil;
self.downloadData = nil;
}
}
I would like to know if there is a better way of doing this. A better algorithm, or a better class to use.
Thanks.