1

对于下载文件,我这样做:

 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);
}];
4

1 回答 1

0

根据此文档,可选的接收数据选择器可以设置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。

还发现这个线程提供了将用于进度回调的代码:

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]));
}];
于 2016-06-03T05:52:38.540 回答