Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to measure download speed on iPhone using cocoa touch

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.

like image 707
pedros Avatar asked Nov 03 '22 16:11

pedros


1 Answers

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;
like image 96
Nishant Avatar answered Nov 08 '22 07:11

Nishant