Can I use google drive sdk with authentication inf

2019-02-14 23:55发布

问题:

We already have a login module uses Google Sign-In sdk. Google Sign-In gives a GIDAuthentication object after login succeed.

Now I want to access user's google drive with google drive sdk which needs a GTMOAuth2Authentication to provide authentication info. So can I use the GIDAuthentication to construct a GTMOAuth2Authentication for drive sdk?

Manually assign the accessToken value seems not working(drive scope added).

回答1:

Yes you can!

Use the following steps:

  1. Follow all the steps to add Google SignIn as described in: https://developers.google.com/identity/sign-in/ios/start-integrating. Make sure you enable the Google Drive API for your project.

  2. When initialising the sign-in object, don't forget to add the Google Drive API scope:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Initialize sign-in
        var configureError: NSError?
        GGLContext.sharedInstance().configureWithError(&configureError)
        assert(configureError == nil, "Error configuring Google services: \(configureError)")
    
        GIDSignIn.sharedInstance().delegate = self
    
        // Use here whatever auth scope you wish (e.g., kGTLAuthScopeDriveReadonly, 
        // kGTLAuthScopeDriveMetadata, etc..)
        // You can obviously append more scopes to allow access to more services,
        // other than Google Drive.
        GIDSignIn.sharedInstance().scopes.append(kGTLAuthScopeDrive)
    
        return true
    }
    
  3. In your AppDelegate (or some other accessible place), add:

    var myAuth: GTMFetcherAuthorizationProtocol? = nil
    
  4. In you signIn delegate function (assuming here it is also set in AppDelegate), add the following code:

    func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
        if (error == nil) {
            // Logged into google services successfully! 
            // Save relevant details from user.authentication to refresh the token when needed.      
    
            // Set GTMOAuth2Authentication authoriser for your Google Drive service
            myAuth = user.authentication.fetcherAuthorizer()
        } else {
            // Error signing into Google services
        }
    }
    
  5. Last, wherever you set your GoogleServiceDrive, you can also set its authoriser, simply by setting:

    let service = GTLServiceDrive()
    service.authorizer = (UIApplication.sharedApplication().delegate as! AppDelegate).myAuth
    
  6. Now you can use the example code by Google

    if let authorizer = service.authorizer, canAuth = authorizer.canAuthorize where canAuth {
        // service is authorised and can be used for queries
    } else {
        // service is not authorised 
    }
    


回答2:

/ Creates the auth controller for authorizing access to Google Drive.
- (GTMOAuth2ViewControllerTouch *)createAuthController
{
    GTMOAuth2ViewControllerTouch *authController;
    authController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:@"https://www.googleapis.com/auth/drive"
                                                                clientID:kClientID
                                                            clientSecret:kClientSecret
                                                        keychainItemName:kKeychainItemName
                                                                delegate:self
                                                        finishedSelector:@selector(viewController:finishedWithAuth:error:)];
    return authController;
}

// Handle completion of the authorization process, and updates the Drive service
// with the new credentials.
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
      finishedWithAuth:(GTMOAuth2Authentication *)authResult
                 error:(NSError *)error
{
    if (error != nil)
    {
        [self showAlert:@"Authentication Error" message:error.localizedDescription];
        self.driveService.authorizer = nil;
    }
    else
    {
        self.driveService.authorizer = authResult;
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
}-(void)loadDriveFiles
{
    NSMutableArray *driveFiles = [[NSMutableArray alloc] init];
    NSMutableArray *downloadFiles = [[NSMutableArray alloc] init];

    GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
    query.q = [NSString stringWithFormat:@"'%@' IN parents", @"root"];
    [self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,
                                                              GTLDriveFileList *files,
                                                              NSError *error) {
        if (error == nil)
        {
            for(id key in files.items) {
                NSString *titleStr = [key valueForKey:@"title"];
                [driveFiles addObject:titleStr];

                NSString *downloadStr = [key valueForKey:@"downloadUrl"];
                [downloadFiles addObject:downloadStr];
            }
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            FilesViewController *filesView = (FilesViewController *)[storyboard instantiateViewControllerWithIdentifier:@"filesView"];
            [filesView initwithName:driveFiles anddownload:downloadFiles];
            [self.navigationController pushViewController:filesView animated:YES];
        }
        else
        {
            NSLog(@"An error occurred: %@", error);
        }
    }];
}