2
votes

I want to integrate with Google Drive in my iOS app.

I've done the code for authorizing and I'm getting the accessToken back, so I wanna know - where to go from there in terms of retrieving the PDF files from Google Drive.

My login code:

- (IBAction)signInButtonTapped:(id)sender {    
    NSURL *issuer = [NSURL URLWithString:kIssuer];
    NSURL *redirectURI = [NSURL URLWithString:kRedirectURI];

    [self logMessage:@"Fetching configuration for issuer: %@", issuer];
    // discovers endpoints

    [OIDAuthorizationService discoverServiceConfigurationForIssuer:issuer
                                                        completion:^(OIDServiceConfiguration *_Nullable configuration, NSError *_Nullable error) {


               if (!configuration) {
                    [self logMessage:@"Error retrieving discovery document: %@", [error localizedDescription]];
                    [self setAuthState:nil];
                    return;
                }

                [self logMessage:@"Got configuration: %@", configuration];

                                                        // builds authentication request
                OIDAuthorizationRequest *request =
                [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration
                                                                                                      clientId:kClientID
                                                                                                        scopes:@[OIDScopeOpenID, OIDScopeProfile]
                                                                                                   redirectURL:redirectURI
                                                                                                  responseType:OIDResponseTypeCode
                                                                                          additionalParameters:nil];
                                                        // performs authentication request
            AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [self logMessage:@"Initiating authorization request with scope: %@", request.scope];

            appDelegate.currentAuthorizationFlow =
            [OIDAuthState authStateByPresentingAuthorizationRequest:request
                                                    presentingViewController:self
                                                                            callback:^(OIDAuthState *_Nullable authState,
                                                                                                                  NSError *_Nullable error) {
                                        if (authState) {

                                            [self setAuthState:authState];

                                            [self logMessage:@"Got authorization tokens. Access token: %@", authState.lastTokenResponse.accessToken];
                                            [self logMessage:@"Got authorization tokens. Refresh Access token %@", authState.refreshToken];



                                            } else {

                                            [self logMessage:@"Authorization error: %@", [error localizedDescription]];

                                            [self setAuthState:nil];

                                        }
            }];}];}
1
You may want to check Downloading Google Documents. The given example demonstrates how to download a Google Document in PDF format using the client libraries. You may also look into table of supported export MIME types to get the corresponding MIME type of every Google Doc Format. For a more detailed information, you may want to check the full iOS documentation. - Teyam
@Sipho Koza, What url needs to be set as redirectURI? I'm stuck here, is it needs to be added to developer console too? Please help. - Bharat Modi
I have composed a medium blog with step by step explanation. Have a look at this medium.com/@kunalgupta1508/… - Kunal Gupta

1 Answers

1
votes

Code reference library: https://github.com/google/google-api-objectivec-client-for-rest

Method for performing Google Drive Services requests.

- (GTLRDriveService *)driveService {
    static GTLRDriveService *service;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
    service = [[GTLRDriveService alloc] init];

    // Turn on the library's shouldFetchNextPages feature to ensure that all items
    // are fetched.  This applies to queries which return an object derived from
    // GTLRCollectionObject.
    service.shouldFetchNextPages = YES;

    // Have the service object set tickets to retry temporary error conditions
    // automatically
    service.retryEnabled = YES;
    });
    return service;
}

After Google Authentication, Authorise driveService using these lines:

In your case,

if (authState) {
    // Creates a GTMAppAuthFetcherAuthorization object for authorizing requests.
                GTMAppAuthFetcherAuthorization *gtmAuthorization =
                [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];

                // Sets the authorizer on the GTLRYouTubeService object so API calls will be authenticated.
                strongSelf.driveService.authorizer = gtmAuthorization;

                // Serializes authorization to keychain in GTMAppAuth format.
                [GTMAppAuthFetcherAuthorization saveAuthorization:gtmAuthorization
                                                toKeychainForName:kKeychainItemName];

    // Your further code goes here
    //
    [self fetchFileList];
}

Then, You can use below method to fetch files from Google Drive:

- (void)fetchFileList {

  __block GTLRDrive_FileList *fileListNew = nil;

  GTLRDriveService *service = self.driveService;

  GTLRDriveQuery_FilesList *query = [GTLRDriveQuery_FilesList query];

  // Because GTLRDrive_FileList is derived from GTLCollectionObject and the service
  // property shouldFetchNextPages is enabled, this may do multiple fetches to
  // retrieve all items in the file list.

  // Google APIs typically allow the fields returned to be limited by the "fields" property.
  // The Drive API uses the "fields" property differently by not sending most of the requested
  // resource's fields unless they are explicitly specified.
  query.fields = @"kind,nextPageToken,files(mimeType,id,kind,name,webViewLink,thumbnailLink,trashed)";

  GTLRServiceTicket *fileListTicket;

  fileListTicket = [service executeQuery:query
                    completionHandler:^(GTLRServiceTicket *callbackTicket,
                                        GTLRDrive_FileList *fileList,
                                        NSError *callbackError) {
    // Callback
    fileListNew = fileList;

  }];
}

Try DriveSample from the reference library, include GTLRDrive Files in your project and you are ready to use above method.

To get the GTMAppAuthFetcherAuthorization working, you've to include the pod "GTMAppAuth" or include the files manually in your project.

Actually above methods are copied from DriveSample example of referenced library and this example is working fine for Drive requests.