使用Cocoa Touch测量iPhone下载速度的最佳方法

5
我正在开发一款应用程序,其中一个功能是测量连接的下载速度。为了实现这个功能,我使用NSURLConnection启动一个大文件的下载,在一段时间后取消下载并进行计算(下载的数据/经过的时间)。 虽然像speedtest.net这样的其他应用程序每次都给出恒定的速度,但我的应用程序波动在2-3 Mbps左右。 基本上,我所做的就是在方法connection:didReceiveResponse:被调用时启动计时器。在调用500次方法connection: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;
    }
}

我想知道是否有更好的方法来做这件事。更好的算法,或更好的类来使用。

谢谢。


你在使用自己的服务器吗? - Jack Humphries
1
Speed Test有许多服务器,拥有超快的互联网连接(要求为100 Mb/s+)。因此,如果有人在不同的国家使用您的应用程序,他们的距离会导致数据传输需要更长的时间,因此应用程序将报告不准确的速度。此外,如果一堆人同时进行测试(不确定您的服务器速度),服务器也可能会变慢,从而导致数据传输需要更长的时间。我建议在Google上找到一个文件并下载它。Google在不同的位置有相当多的数据中心。 - Jack Humphries
谷歌文件是个好主意。这个应用只针对我的国家(巴西),所以我考虑使用全国各地的大学服务器。但是,我仍然无法想出一种更精确的测速方法。我不知道speedtest.net移动应用程序是如何实现的。 - pedros
你知道在iOS中还有其他的方法吗?也许有一种更原始的下载文件的方式? - pedros
请查看此链接,它将满足您的需求:https://dev59.com/B2Uq5IYBdhLWcg3wY_ka - user3223527
显示剩余2条评论
1个回答

2

一旦您开始下载,立即捕获当前系统时间并将其存储为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;

嘿 - 我怎样才能以 Mbps 的形式获取这个值? - Asi Givati
3
只需将“downloadSpeed”除以2^20即可!你会得到MBps。 - Nishant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接