のドキュメントにNSProgress
よると、-[NSProgress localizedAdditionalDescription]
ダウンロード速度と残り時間を報告できることがわかります。
1.61 GB の 3.22 GB (2 KB/秒) — 残り 2 分
NSProgress
ただし、 を に関連付けると、これらの詳細を取得できませんNSURLSessionDownloadTask
。これが私のコードです:
Downloader.h
@interface Downloader : NSObject
@property NSProgress *overallProgress;
-(void)startDownload;
@end
Downloader.m
- (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];
}
ダウンロードObserver.m
-(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]);
}
これは以下のみを出力します:
0/100
100 バイトのゼロ KB
localizedAdditionalDescription
ダウンロード速度と残り時間を印刷するにはどうすればよいですか?