我正在制作一个应用程序,我想提供的功能之一是测量连接的下载速度。为了得到这个,我使用 NSURLConnection 开始下载一个大文件,并在一段时间后取消下载并进行计算(下载的数据/经过的时间)。
虽然其他应用程序(例如 speedtest.net)每次都提供恒定的速度,但我的应用程序或多或少波动 2-3 Mbps。
基本上我正在做的是,在调用方法connection:didReceiveResponse:时启动计时器。在调用方法 connect: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;
}
}
我想知道是否有更好的方法来做到这一点。更好的算法,或者更好的类来使用。
Thanks.
一旦开始下载,捕获当前系统时间并将其存储为startTime
。然后,您需要做的就是计算下载过程中任意时刻的数据传输速度。只需再次查看系统时间并将其用作currentTime
计算到目前为止花费的总时间。
下载速度 = bytesTransferred / (当前时间 - 开始时间)
像这样:
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)