Best way to measure download speed on iPhone using cocoa touch

依然范特西╮ 提交于 2020-01-13 03:15:30

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/12271502/best-way-to-measure-download-speed-on-iphone-using-cocoa-touch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!