DimonDeveloper
DimonDeveloper

Reputation: 137

How to get GTMSessionFetcher download progress

For download a file, i do like this:

 GTMSessionFetcher *fetcher = [self.service.fetcherService fetcherWithURLString:url];
    [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
        {
    [data writeToFile:localFilePath atomically:YES];
    }];

File successfully downloaded but i can't get the download progress if you do like this.

fetcher.downloadProgressBlock  = ^(int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite)
    {
        NSLog(@"bytesWritten = %lld",bytesWritten);
        NSLog(@"totalBytesWritten = %lld",totalBytesWritten);
        NSLog(@"totalBytesExpectedToWrite = %lld",totalBytesExpectedToWrite);
    };

What am I doing wrong?

I found working solution.

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

Upvotes: 1

Views: 1308

Answers (1)

abielita
abielita

Reputation: 13469

Based from this documentation, the optional received data selector can be set with setReceivedDataSelector and should have the signature:

- (void)myFetcher:(GTMSessionFetcher *)fetcher receivedData:(NSData *)dataReceivedSoFar;

Here is the sample code:

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 will return -1 if the size of the downloaded file is unknown.

Also found this thread that provided code that will be used for callbacks of the progress:

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

Upvotes: 0

Related Questions