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

我正在制作一个应用程序,其中我想要提供的function之一是测量连接的下载速度。 为此,我使用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; } } 

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

谢谢。

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