为了下载文件,我喜欢这样:
GTMSessionFetcher *fetcher = [self.service.fetcherService fetcherWithURLString:url];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
{
[data writeToFile:localFilePath atomically:YES];
}];
文件已成功下载,但如果您这样做,我无法获得下载进度。
fetcher.downloadProgressBlock = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite)
{
NSLog(@"bytesWritten = %lld",bytesWritten);
NSLog(@"totalBytesWritten = %lld",totalBytesWritten);
NSLog(@"totalBytesExpectedToWrite = %lld",totalBytesExpectedToWrite);
};
我做错了什么?
我找到了工作解决方案。
float totalBytesExpectedToWrite = [file.size floatValue]; //file - it's GTLDriveFile to download
[fetcher setReceivedProgressBlock:^(int64_t bytesWritten, int64_t totalBytesWritten)
{
NSLog(@"Download progress - %.0f",(totalBytesWritten * 100)/totalBytesExpectedToWrite);
}];
答案 0 :(得分:0)
根据此documentation,可选的接收数据选择器可以设置为setReceivedDataSelector
并且应该具有签名:
- (void)myFetcher:(GTMSessionFetcher *)fetcher receivedData:(NSData *)dataReceivedSoFar;
以下是示例代码:
self.fetcher = [GTMHTTPFetcher fetcherWithRequest:request];
[self.fetcher setReceivedDataBlock:^(NSData *data) {
float percentTransfered = self.fetcher.downloadedLength * 100.0f / self.fetcher.response.expectedContentLength;
// Do something with progress
}
如果下载文件的大小未知, expectedContentLength
将返回-1。
还发现这个thread提供了用于进展回调的代码:
GTMHTTPFetcher *fetcher =
[self.driveService.fetcherService fetcherWithURLString:downloadURL];
GTLDriveFile *file = [driveFiles objectAtIndex:indexPath.row];
[fetcher setReceivedDataBlock:^(NSData *data) {
NSLog(@"%f%% Downloaded", (100.0 / [file.fileSize longLongValue] * [data length]));
}];