iOS Google Drive集成 [英] iOS Google Drive integration

查看:893
本文介绍了iOS Google Drive集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iOS应用中与Google云端硬盘进行整合。

我已经完成授权的代码,并且正在收到accessToken,所以我想要知道 - 从Google Drive中检索PDF文件的位置。



我的登录码:

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

[self logMessage:@获取发行者的配置:%@,发行者];
//发现端点

[OIDAuthorizationService discoverServiceConfigurationForIssuer:issuer
完成:^(OIDServiceConfiguration * _Nullable配置,NSError * _Nullable错误){


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

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

//建立认证请求
OIDAuthorizationRequest * request =
[[OIDAuthorizationRequest alloc] initWithConfiguration:配置
clientId:kClientID
作用域:@ [OIDScopeOpenID, OIDScopeProfile]
redirectURL:redirectURI
responseType:OIDResponseTypeCode
additionalParameters:nil];
//执行认证请求
AppDelegate * appDelegate =(AppDelegate *)[UIApplication sharedApplication] .delegate;
[self logMessage:@使用scope:%@启动授权请求,request.scope];

appDelegate.currentAuthorizationFlow =
[OIDAuthState authStateByPresentingAuthorizationRequest:请求
presentsViewController:self
回调:^(OIDAuthState * _Nullable authState,
NSError * _Nullable error) {
if(authState){

[self setAuthState:authState];

[self logMessage:@got authorized token to。access token:%@,authState.lastTokenResponse.accessToken];
[self logMessage:@got authorized token to。Refresh Access token%@,authState.refreshToken];



} else {

[self logMessage:@授权错误:%@,[error localizedDescription]];

[self setAuthState:nil];

$ b}];}];}


解决方案

代码参考库: https:/ /github.com/google/google-api-objectivec-client-for-rest



执行Google云端硬盘服务请求的方法。

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

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

//打开库的shouldFetchNextPages功能以确保所有项目
//被提取,这适用于返回从
// GTLRCollectionObject派生的对象的查询
service.shouldFetchNextPages = YES;

//将服务对象设置为ticket重试临时错误条件
//自动
service.retryEnabled = YES;
});
退货服务;
}

Google认证后,使用以下行授权driveService:



在你的情况下,

  if(authState){
//创建一个用于授权请求的GTMAppAuthFetcherAuthorization对象。
GTMAppAuthFetcherAuthorization * gtmAuthorization =
[[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];

//在GTLRYouTubeService对象上设置授权者,这样API调用将被认证。
strongSelf.driveService.authorizer = gtmAuthorization;

//以GTMAppAuth格式将授权序列化到钥匙串。
[GTMAppAuthFetcherAuthorization saveAuthorization:gtmAuthorization
toKeychainForName:kKeychainItemName];

//你的进一步代码在这里
//
[self fetchFileList];
}

然后,您可以使用下面的方法从Google云端硬盘中提取文件:

   - (void)fetchFileList {

__block GTLRDrive_FileList * fileListNew = nil;

GTLRDriveService * service = self.driveService;

GTLRDriveQuery_FilesList * query = [GTLRDriveQuery_FilesList query];

//由于GTLRDrive_FileList是从GTLCollectionObject派生的,并且服务
//属性shouldFetchNextPages已启用,因此可以执行多次获取到
//检索文件列表中的所有项目。

// Google API通常允许返回的字段受到字段属性的限制。
// Drive API使用fields属性的方式不同,除非明确指定,否则不会发送大部分请求的
//资源的字段。
query.fields = @kind,nextPageToken,files(mimeType,id,kind,name,webViewLink,thumbnailLink,trashed);

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

}];
}

尝试参考库中的DriveSample,将GTLRDrive Files包含在您的项目中,准备使用上面的方法。



要使GTMAppAuthFetcherAuthorization正常工作,您必须包含GTMAppAuth窗格或手动将文件包含在项目中。



实际上面的方法是从引用库的DriveSample例子中复制的,并且这个例子对驱动器请求工作正常。


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

                                        }
            }];}];}

解决方案

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.

这篇关于iOS Google Drive集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆