Best way to measure download speed on iPhone with cocoa touch

I am creating an application in which one of the functions I want to offer is to measure the connection download speed. To get this, I use NSURLConnection to start downloading a large file and after a while cancel the download and do the calculation (data uploaded / time passed). While other applications, such as speedtest.net, give a constant speed every time, mine fluctuates 2-3 Mbps more or less.

Basically, what I do is start the timer when the method connection is called: didReceiveResponse :. After 500 calling the connection method: 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;
    }
}

, . .

.

+5
1

, startTime. , , . currentTime, , .

downloadSpeed ​​= bytesTransferred/(currentTime - startTime)

:

static NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];    
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
double downloadSpeed = totalBytesWritten / (currentTime - startTime);

NSURLConnectionDownloadDelegate:

- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;
+1

All Articles