【问题标题】:how to get the download time of a video from server in device in milliseconds in iOS如何在iOS中以毫秒为单位从设备中的服务器获取视频的下载时间
【发布时间】:2014-09-22 06:16:27
【问题描述】:

我的服务器上有视频,我想知道我的视频需要多长时间才能从设备中的服务器下载。这样我就可以计算下载时间并检查服务器是否很慢。任何帮助将不胜感激。

这是我的代码:

  NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:[[Configuration sharedInstance] fatchTimeOut]];

  [GMURLConnection sendAsynchronousRequest:request queue:self.operationQueue type:type withSubType:subType completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

 //**********************Success Handling ********************
    if (type == OperationTypeMeta) {
        failCount = 0;
        NSError *error = nil;

        NSArray *serverResponse=[NSArray array];
        if(data)
            serverResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
       }];

【问题讨论】:

  • 请出示您的代码

标签: ios objective-c ios7 xcode6


【解决方案1】:

您不能使用 sendAsynchronousRequest 和监视连接状态。根据apple docs

使用完成处理程序块检索 URL 的内容:如果 您不需要监视请求的状态,而只需要 当数据已完全接收时执行一些操作,您可以 调用 sendAsynchronousRequest:queue:completionHandler:,传递一个块 处理结果。

所以你必须实现 NSURLConnection 委托。如果你喜欢块样式(我真的很喜欢),只需创建实现委托方法的新类,并将 NSURLRequest、状态块和完成块作为参数,并在适当的委托方法中调用它们。这样,您将拥有带有状态更新的块式异步请求。

如果您不知道如何测量剩余时间 - 每次调用didReceiveData: 方法时将数据长度附加到类变量,并计算自上次方法接收以来经过了多少时间。这样你就有了速度(每秒字节数)。知道你下载的文件有多大,只需将剩余大小除以你的速度,你就会得到剩余时间。有一些简洁的算法可以获得整洁/稳定的剩余时间,而不是仅仅从 30 秒跳到 2 分钟(如果我们假设我们的互联网连接很棘手)。我个人使用了@Ben Dolman 在here 上发布的解决方案:

averageSpeed = SMOOTHING_FACTOR * lastSpeed + (1-SMOOTHING_FACTOR) * averageSpeed;

通过一些调整和使用 SMOOTHING_FACTOR,我取得了很好的成绩。

【讨论】:

  • 非常感谢。我会尝试并回复您。
【解决方案2】:

我建议你使用AFHTTPRequestOperation。像这样:

AFHTTPRequestOperation* operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){

        }];

【讨论】:

  • 我无法使用外部 sdk。我已经有一个名为 sendasynchronousblock 的块用于从服务器获取数据。 [GMURLConnection sendAsynchronousRequest:request queue:self.operationQueue type:type withSubType:subType completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {}];
【解决方案3】:

您可以将 NSURLConnection 与它的委托一起使用。

当你首先下载文件时,你会从服务器得到总文件大小的响应

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
     _expectedContentLength = [response expectedContentLength];
        if (_expectedContentLength==NSURLResponseUnknownLength)
            _expectedContentLength = 0;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 之后,您可以根据下载部分文件和整个文件大小所花费的时间来计算下载时间

【讨论】:

  • 实际上我在这里使用了 sendAsynchronousRequest 块。据你说,我将不得不创建一个 http 连接。我们可以得到块内的时间吗?
猜你喜欢
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多