我正在开发一款应用程序,其中一个功能是测量连接的下载速度。为了实现这个功能,我使用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;
}
}
我想知道是否有更好的方法来做这件事。更好的算法,或更好的类来使用。
谢谢。