使用cocoa touch测量iPhone下载速度的最佳方法

ped*_*ros 5 iphone cocoa-touch nsurlconnection ios

我正在制作一个应用程序,其中我想要提供的功能之一是测量连接的下载速度.为此,我使用NSURLConnection开始下载大文件,并在一段时间后取消下载并进行计算(数据下载/时间已过).虽然像speedtest.net这样的其他应用程序每次都会提供恒定的速度,但是我的或多或少会有2-3 Mbps的波动.

基本上我正在做的是,在调用方法连接:didReceiveResponse:时启动计时器.500调用方法连接后:didReceiveData:我取消下载,停止计时器并计算速度.

这是代码:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更好的方法来做到这一点.一个更好的算法,或更好的类使用.

谢谢.

Nis*_*ant 2

一旦开始下载,捕获当前系统时间并将其存储为startTime. 然后,您需要做的就是计算下载过程中任意时刻的数据传输速度。只需再次查看系统时间并将其用作currentTime计算到目前为止所花费的总时间即可。

下载速度 = bytesTransferred / (当前时间 - 开始时间)

像这样:

static NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];    
NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
double downloadSpeed = totalBytesWritten / (currentTime - startTime);
Run Code Online (Sandbox Code Playgroud)

您可以从以下位置使用此方法NSURLConnectionDownloadDelegate

- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes;
Run Code Online (Sandbox Code Playgroud)

  • @AsiGivati:只需将“下载速度”除以 2^20 即可!您将获得 MBps (3认同)