2017-01-13 4 views
2

Я хочу интегрироваться с Google Диском в моем приложении для iOS.iOS Google Drive интеграция

Я сделал код для авторизации, и я получаю accessToken обратно, поэтому я хочу знать - куда идти оттуда с точки зрения получения файлов PDF с Google Диска.

Мой код Логин:

- (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]; 

             } 
      }];}];} 
+0

Возможно, вы захотите проверить [Загрузка документов Google] (https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents). Данный пример демонстрирует, как загрузить документ Google в формате PDF с использованием клиентских библиотек. Вы также можете посмотреть таблицу поддерживаемых типов MIME экспорта, чтобы получить соответствующий тип MIME для каждого формата Google Doc. Для получения более подробной информации вы можете проверить [полную документацию iOS] (https://developers.google.com/drive/ios/). – Teyam

+0

@Sipho Koza, Какой url нужно установить как redirectURI? Я застрял здесь, нужно ли его добавить в консоль разработчика тоже? Пожалуйста помоги. –

ответ

1

Код ссылки библиотека: https://github.com/google/google-api-objectivec-client-for-rest

Способ выполнения Google Drive служб запросов.

- (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; 
} 

После Google проверки подлинности Авторизоваться driveService используя эти строки:

В вашем случае,

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

Затем вы можете использовать ниже метод для извлечения файлов из 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; 

    }]; 
} 

Попробуйте DriveSample из справочной библиотеки, включите файлы GTLRDrive в свой проект, и вы снова ади использовать вышеописанный метод.

Чтобы получить работу GTMAppAuthFetcherAuthorization, вы должны включить модуль «GTMAppAuth» или включить файлы вручную в свой проект.

Фактически выше методы копируются из примера справочной библиотеки DriveSample, и этот пример отлично подходит для запросов на диск.

+1

Благодарим за отзыв .. это работало идеально для меня. –

+0

Рад, что это помогло! –

+0

@GauravSingla Вы знаете, как получить идентификатор определенной папки? и как загружать изображения на диск? –