Objective-C Google Drive: Download a File (Stream to the Filesystem)

Back to Index

Downloads the content of a file by ID. (In this example the file id = 1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl) The file is streamed directly to the filesystem. Note: The alt=media query param must be used to download the file content (as opposed to the file metadata).

Documentation: https://developers.google.com/drive/v3/reference/files/get


#import <CkoRest.h>
#import <CkoOAuth2.h>
#import <CkoStringBuilder.h>
#import <CkoStream.h>

CkoRest *rest = [[CkoRest alloc] init];
BOOL success;

//   Provide a previously obtained OAuth2 access token.
CkoOAuth2 *oauth2 = [[CkoOAuth2 alloc] init];
oauth2.AccessToken = @"OAUTH2_ACCESS_TOKEN";
[rest SetAuthOAuth2: oauth2];

success = [rest Connect: @"www.googleapis.com" port: [NSNumber numberWithInt: 443] tls: YES autoReconnect: YES];
if (success != YES) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

[rest AddQueryParam: @"includeTeamDriveItems" value: @"true"];
[rest AddQueryParam: @"supportsTeamDrives" value: @"true"];
[rest AddQueryParam: @"alt" value: @"media"];

//  First send the HTTP request.
success = [rest SendReqNoBody: @"GET" uriPath: @"/drive/v3/files/1R_70heIyzIAu1_u0prXbYcaIiJRVkgBl"];
if (success != YES) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

//  Read the response header.  If the response status code is success, stream to the file.
//  Otherwise receive the error response text.
int statusCode = [[rest ReadResponseHeader] intValue];
if (statusCode < 0) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

if (statusCode != 200) {
    NSLog(@"%@%d",@"Received error response code: ",statusCode);
    //  Read the error response body.
    CkoStringBuilder *sbErrResponse = [[CkoStringBuilder alloc] init];
    success = [rest ReadRespSb: sbErrResponse];
    if (success != YES) {
        NSLog(@"%@",rest.LastErrorText);
        return;
    }

    NSLog(@"%@%@",@"Error response:",[sbErrResponse GetAsString]);
    return;
}

//  Stream the response body to the output file.
CkoStream *respBodyStream = [[CkoStream alloc] init];
respBodyStream.SinkFile = @"/someDirectory/penguins.jpg";
success = [rest ReadRespBodyStream: respBodyStream autoSetStreamCharset: YES];
if (success != YES) {
    NSLog(@"%@",rest.LastErrorText);
    return;
}

NSLog(@"%@",@"Example Completed.");