【发布时间】:2015-09-14 15:36:05
【问题描述】:
我正在制作一个应用程序,其中我想提供的功能之一是测量连接的下载速度。为此,我使用 NSURLConnection 开始下载一个大文件,并在一段时间后取消下载并进行计算(下载的数据/经过的时间)。 虽然 speedtest.net 等其他应用程序每次都提供恒定的速度,但我的或多或少会波动 2-3 Mbps。
基本上我正在做的是,在方法 connection:didReceiveResponse: 被调用时启动计时器。方法connection:didReceiveData 500调用后:我取消下载,停止定时器,计算速度。
代码如下:
- (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;
}
}
我想知道是否有更好的方法来做到这一点。更好的算法,或者更好的类来使用。
谢谢。
【问题讨论】:
-
您使用的是自己的服务器吗?
-
我正在使用我所在城市的大学服务器。
-
Speed Test 有许多服务器具有极快的 Internet 连接(要求为 100 Mb/s +)。因此,如果有人在不同的国家并使用您的应用程序,他们的距离将导致数据传输时间更长,因此应用程序将报告不准确的速度。此外,如果一群人同时执行此操作(不确定服务器的速度),服务器可能会变慢,从而导致数据传输时间更长。我建议在 Google 上找到一个文件并下载它。谷歌在不同的地方有很多数据中心。
-
google 文件是个好主意。该应用程序仅针对我的国家(巴西),所以我正在考虑使用来自全国各地的大学服务器。但是,我仍然想不出一种更精确的方法来测量速度。我不知道speedtest.net移动应用是怎么做到的。
-
NSURLConnection 并不理想,因为有效负载和标头会被 gzip 压缩(通常)。所以你得到的数字大多是似是而非的。也就是说,如果您下载的文件已经被压缩,那么重新压缩不会改变大小。
标签: iphone ios cocoa-touch nsurlconnection