【问题标题】:Best way to measure download speed on iPhone using cocoa touch使用 Cocoa touch 在 iPhone 上测量下载速度的最佳方法
【发布时间】: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


【解决方案1】:

开始下载后,立即捕获当前系统时间并将其存储为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 为单位的值?
  • @AsiGivati:只需将“下载速度”除以 2^20!您将获得 MBps
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 2012-08-28
  • 2011-09-13
  • 2023-03-14
  • 2015-07-28
相关资源
最近更新 更多