首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSProgress查找下载速度和剩余时间

使用NSProgress查找下载速度和剩余时间
EN

Stack Overflow用户
提问于 2014-02-04 14:17:41
回答 1查看 9K关注 0票数 11

根据NSProgress,我看到-[NSProgress localizedAdditionalDescription]可以报告下载速度和剩余时间,例如:

1.61 GB 3.22 GB (2KB/秒)-剩余2分钟

但是,当我将NSProgressNSURLSessionDownloadTask相关联时,我无法获得这些细节。这是我的密码:

Downloader.h

代码语言:javascript
复制
@interface Downloader : NSObject
@property NSProgress *overallProgress;
-(void)startDownload;
@end

Downloader.m

代码语言:javascript
复制
- (void)startDownload {

    self.overallProgress = [NSProgress progressWithTotalUnitCount:100];

    [self.overallProgress setKind:NSProgressKindFile];
    [self.overallProgress setUserInfoObject:NSProgressFileOperationKindKey forKey:NSProgressFileOperationKindDownloading];


    [self.overallProgress becomeCurrentWithPendingUnitCount:100];
    [self work1];
    [self.overallProgress resignCurrent];
}

- (void)work1 {

    NSProgress *firstTaskProgress = [NSProgress progressWithTotalUnitCount:1];
    [firstTaskProgress setKind:NSProgressKindFile];
    [firstTaskProgress setUserInfoObject:NSProgressFileOperationKindKey forKey:NSProgressFileOperationKindDownloading];

    NSURL *downloadURL = [NSURL URLWithString:@"http://ipv4.download.thinkbroadband.com/200MB.zip"];
    NSURL *destinationDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
    NSURL *destinationURL = [destinationDirectory URLByAppendingPathComponent:[downloadURL lastPathComponent]];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDownloadTask *fileDownloadTask =
    [session downloadTaskWithURL:downloadURL
               completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error){

                   [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:NULL];

                   [[NSFileManager defaultManager] moveItemAtURL:location toURL:destinationURL error:nil];

                   [firstTaskProgress setCompletedUnitCount:1];
               }];

    [fileDownloadTask resume];
}

DownloadObserver.m

代码语言:javascript
复制
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    downloader = [Downloader new];

    [downloader addObserver:self
                 forKeyPath:@"overallProgress.fractionCompleted"
                    options:NSKeyValueObservingOptionNew
                    context:NULL];

    [downloader startDownload];

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"%@", [downloader.overallProgress localizedAdditionalDescription]);
}

这只会打印出来:

100中的0 100字节的零KB

如何让localizedAdditionalDescription打印下载速度和剩余时间?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-12 08:03:19

首先,totalUnitCount应该对应文件的大小(以字节为单位)。在下载过程中,我们修改了completedUnitCount,它反映在localizedAdditionalDescription上。NSProgressKindFile是将这些值格式化为文件大小的提示。

要正确设置进度,我们需要使用NSURLSessionDownloadDelegate方法而不是块处理程序。在-URLSession: downloadTask: didWriteData: totalBytesWritten: totalBytesExpectedToWrite:中,我们有所有要启动(totalBytesExpectedToWrite)和更新(totalBytesWritten)进度的信息。

代码语言:javascript
复制
static void *myContext = &myContext;

- (void)download {
    NSURL *downloadURL = [NSURL URLWithString:@"http://ipv4.download.thinkbroadband.com/10MB.zip"];
    NSURLSession *session =
    [NSURLSession
     sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
     delegate:self
     delegateQueue:[NSOperationQueue mainQueue]];

    [[session downloadTaskWithURL:downloadURL] resume];
}

#pragma mark - url session download delegate

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    if (!_progress) {
        _progress = [NSProgress progressWithTotalUnitCount:totalBytesExpectedToWrite];
        _progress.kind = NSProgressKindFile;
        [_progress addObserver:self forKeyPath:@"fractionCompleted" options:0 context:myContext];
    }

    _progress.completedUnitCount = totalBytesWritten;
    //[_overallProgress setUserInfoObject:@1024 forKey:NSProgressEstimatedTimeRemainingKey];
}

- (void)URLSession:(NSURLSession *)session 
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    [_progress removeObserver:self forKeyPath:@"fractionCompleted"];
    _progress = nil;
    NSLog(@"finished: %@", location);
}

-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary *)change
                      context:(void *)context
{
    if (context == myContext) {
        self.label.text = [_progress localizedAdditionalDescription];
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

事实上,NSProgress不做任何计算。它只是根据userInfo和其他类属性格式化本地化描述。请参阅文档中的常量部分。您可以使用这些值并比较本地化的描述输出。

如果要显示剩余的下载时间,可以使用NSProgressEstimatedTimeRemainingKey。坏消息是,您需要手动计算剩余时间。参考资料:如何估算下载剩余时间(准确)?

我尝试设置NSProgressThroughputKey,它指示以每秒字节为单位的数据处理速度。我原以为NSProgress会计算剩余时间,但没有发生。

还请参阅AFNetworking源AFURLSessionManagerTaskDelegate使用NSProgress实例进行上载和下载任务。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21554949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档