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.
As soon as you start the download, capture the current system time and store it as the startTime
. Then, all you need to do is calculate data transfer speed at any point during the download. Just look at the system time again and use it as the currentTime
to calculate the total time spent so far.
downloadSpeed = bytesTransferred / (currentTime - startTime)
Like this:
static NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
double downloadSpeed = totalBytesWritten / (currentTime - startTime);
You can use this method from NSURLConnectionDownloadDelegate
:
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With