从Google云端硬盘列出所有文件夹内容 [英] Listing All Folder content from Google Drive

查看:136
本文介绍了从Google云端硬盘列出所有文件夹内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我已经使用博士从谷歌驱动器编辑示例代码将Google Dive与我的应用程序集成在一起。但我无法查看存储在我的Google云端硬盘帐户中的所有文件。



//我试过了这个

   - (void)getFileListFromSpecifiedParentFolder 
{
GTLQueryDrive * query2 = [GTLQueryDrive queryForChildrenListWithFolderId:@root];
query2.maxResults = 1000;


[self.driveService executeQuery:query2
completionHandler:^(GTLServiceTicket * ticket,
GTLDriveChildList * children,NSError * error)
{
NSLog(@\\\
Google Drive:文件夹中的文件数量:%d,children.items.count);

if(!children.items.count)
{
return;


if(error == nil)
{
for(GTLDriveChildReference * child in children)
{

GTLQuery * query = [GTLQueryDrive queryForFilesGetWithFileId:child.identifier];
[self.driveService executeQuery:query completionHandler:^(GTLServiceTicket * ticket,
GTLDriveFile * file,
NSError * error)
{
NSLog(@\ nfile name =%@,file.originalFilename);}];
}
}
}];

//我想在NSLog中显示所有内容...

解决方案

1。如何从Google Drive获取所有文件



首先在 viewDidLoad:方法检查用于身份验证

   - (void)viewDidLoad 
{
[self checkForAuthorization];
}

以下是所有方法的定义:

  //此方法将检查用户身份验证
//如果他没有登录,那么它将会处于其他状态,并将显示登录viewController
- (void)checkForAuthorization
{
//检查授权。
GTMOAuth2Authentication * auth =
[GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientId
clientSecret:kClientSecret];
if([auth canAuthorize])
{
[self isAuthorizedWithAuthentication:auth];
}
else
{
SEL finishedSelector = @selector(viewController:finishedWithAuth:error :);
GTMOAuth2ViewControllerTouch * authViewController =
[[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive
clientID:kClientId
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:finishedSelector];

[self presentViewController:authViewController animated:YES completion:nil];



//这个方法将在登录后调用
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth错误:(NSError *)错误
{
[self dismissViewControllerAnimated:YES completion:nil];

if(error == nil)
{
[self isAuthorizedWithAuthentication:auth];



//如果everthing没有问题,那么使用auth
初始化driveServices(void)isAuthorizedWithAuthentication:(GTMOAuth2Authentication *)auth
{
[[self driveService] setAuthorizer:auth];

//最后在这里你可以加载所有文件
[self loadDriveFiles];


- (GTLServiceDrive *)driveService
{
static GTLServiceDrive * service = nil;

if(!service)
{
service = [[GTLServiceDrive alloc] init];

//让服务对象设置票据以获取提要的连续页面
//,因此我们不需要手动提取它们。
service.shouldFetchNextPages = YES;

//让服务对象设置票据以自动重试临时错误条件
//。
service.retryEnabled = YES;
}

退货服务;
}

//从Google Drive加载所有文件的方法
- (void)loadDriveFiles
{
GTLQueryDrive * query = [GTLQueryDrive queryForFilesList];
query.q = [NSString stringWithFormat:@'%@'IN parents,@root];
// root用于根文件夹将其替换为文件夹标识符以便获取任何特定文件夹

[self.driveService executeQuery:query completionHandler:^(GTLServiceTicket * ticket,
GTLDriveFileList *文件,
NSError *错误){
if(error == nil)
{
driveFiles = [[NSMutableArray alloc] init];
[driveFiles addObjectsFromArray:files.items];

//现在你有根文件夹
的所有文件(驱动文件中的GTLDriveFile *文件)
NSLog(@File is%@,file.title);
}
else
{
NSLog(@An error occurred:%@,error);
}
}];

注意:应该是 kGTLAuthScopeDrive

  [[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive 
clientID:kClientId
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:finishedSelector];

2。如何下载特定文件



因此,您必须使用 GTMHTTPFetcher 。首先获取该文件的下载URL。

  NSString * downloadedString = file.downloadUrl; //文件是GTLDriveFile 
GTMHTTPFetcher * fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadedString];
[fetcher beginFetchWithCompletionHandler:^(NSData * data,NSError * error)
{
if(error == nil)
{
if(data!= nil) {
//你已经成功下载了这个文件,它的名字是
// NSString * name = file.title;



{
NSLog(@Error - %@,error.description)
}
}];

注意:如果发现downloadedStringnull或者空只是看一下file.JSON有exportsLinks数组,那么你可以用它们中的一个来获取文件。

3。如何上传特定文件夹中的文件:这是一个上传图片的例子。

   - (void)uploadImage :(UIImage *)image 
{
//我们需要数据将其上传,以便将其转换为数据
//如果您从任何路径获取文件,则使用dataWithContentsOfFile:方法
NSData * data = UIImagePNGRepresentation(image);

//定义mimeType
NSString * mimeType = @image / png;

//这只是因为你可以给它任意的名字
NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@dd-MMM-yyyy -hh-mm-ss];
NSString * fileName = [df stringFromDate:[NSDate date]];
fileName = [fileName stringByAppendingPathExtension:@png];

//像这样初始化newFile
GTLDriveFile * newFile = [[GTLDriveFile alloc] init];
newFile.mimeType = mimeType;
newFile.originalFilename = fileName;
newFile.title = fileName;

//查询和上传参数
GTLUploadParameters * uploadParameters = [GTLUploadParameters uploadParametersWithData:data MIMEType:mimeType];
GTLQueryDrive * query = [GTLQueryDrive queryForFilesInsertWithObject:newFile uploadParameters:uploadParameters];

//这是为了上传到特定的文件夹,我为根文件夹设置了root。
//你可以给该文件夹上传任何folderIdentifier
GTLDriveParentReference * parentReference = [GTLDriveParentReference object];
parentReference.identifier = @root;
newFile.parents = @ [parentReference];

//最后这是上传文件的方法
[[self driveService] executeQuery:query completionHandler:^(GTLServiceTicket * ticket,id object,NSError * error){

if(error){
NSLog(@Error:%@,error.description);
}
else {
NSLog(@文件已成功上传到根文件夹中。);
}
}];
}


Hi I have integrated google Dive with my app using Dr. Edit sample code from google drive. But i am not able to view all the files, which are stored in my Google Drive account.

// I have tried this

-(void)getFileListFromSpecifiedParentFolder 
{
GTLQueryDrive *query2 = [GTLQueryDrive queryForChildrenListWithFolderId:@"root"];
query2.maxResults = 1000;


[self.driveService executeQuery:query2
              completionHandler:^(GTLServiceTicket *ticket,
                                  GTLDriveChildList *children, NSError *error) 
{
 NSLog(@"\nGoogle Drive: file count in the folder: %d",   children.items.count);

if (!children.items.count) 
{
    return ;
}

if (error == nil) 
{
for (GTLDriveChildReference *child in children) 
{

GTLQuery *query = [GTLQueryDrive queryForFilesGetWithFileId:child.identifier];
[self.driveService executeQuery:query                          completionHandler:^(GTLServiceTicket *ticket,
                             GTLDriveFile *file,
                             NSError *error) 
{
NSLog(@"\nfile name = %@", file.originalFilename);}];
                      }
                  }
              }];
 }

//I want to Display All content in NSLog...

解决方案

1. How to get all files from Google Drive.

First in viewDidLoad: method check for authentication

-(void)viewDidLoad
{
    [self checkForAuthorization];
}

And here is the definition of all methods:

// This method will check the user authentication
// If he is not logged in then it will go in else condition and will present a login viewController
-(void)checkForAuthorization
{
    // Check for authorization.
    GTMOAuth2Authentication *auth =
    [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
                                                          clientID:kClientId
                                                      clientSecret:kClientSecret];
    if ([auth canAuthorize])
    {
        [self isAuthorizedWithAuthentication:auth];
    }
    else
    {
        SEL finishedSelector = @selector(viewController:finishedWithAuth:error:);
        GTMOAuth2ViewControllerTouch *authViewController =
        [[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive
                                               clientID:kClientId
                                           clientSecret:kClientSecret
                                       keychainItemName:kKeychainItemName
                                               delegate:self
                                       finishedSelector:finishedSelector];

        [self presentViewController:authViewController animated:YES completion:nil];
    }
}

// This method will be call after logged in
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth: (GTMOAuth2Authentication *)auth error:(NSError *)error
{
    [self dismissViewControllerAnimated:YES completion:nil];

    if (error == nil)
    {
        [self isAuthorizedWithAuthentication:auth];
    }
}

// If everthing is fine then initialize driveServices with auth
- (void)isAuthorizedWithAuthentication:(GTMOAuth2Authentication *)auth
{
    [[self driveService] setAuthorizer:auth];

    // and finally here you can load all files
    [self loadDriveFiles];
}

- (GTLServiceDrive *)driveService
{
    static GTLServiceDrive *service = nil;

    if (!service)
    {
        service = [[GTLServiceDrive alloc] init];

        // Have the service object set tickets to fetch consecutive pages
        // of the feed so we do not need to manually fetch them.
        service.shouldFetchNextPages = YES;

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

    return service;
}

// Method for loading all files from Google Drive
-(void)loadDriveFiles
{
    GTLQueryDrive *query = [GTLQueryDrive queryForFilesList];
    query.q = [NSString stringWithFormat:@"'%@' IN parents", @"root"];
    // root is for root folder replace it with folder identifier in case to fetch any specific folder

    [self.driveService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,
                                                          GTLDriveFileList *files,
                                                          NSError *error) {
        if (error == nil)
        {
            driveFiles = [[NSMutableArray alloc] init];
            [driveFiles addObjectsFromArray:files.items];

            // Now you have all files of root folder
            for (GTLDriveFile *file in driveFiles)
                 NSLog(@"File is %@", file.title);
        }
        else
        {
            NSLog(@"An error occurred: %@", error);
        }
    }];
}

Note: For get full drive access your scope should be kGTLAuthScopeDrive.

[[GTMOAuth2ViewControllerTouch alloc] initWithScope:kGTLAuthScopeDrive
                                           clientID:kClientId
                                       clientSecret:kClientSecret
                                   keychainItemName:kKeychainItemName
                                           delegate:self
                                   finishedSelector:finishedSelector];

2. How to download a specific file.

So for this you will have to use GTMHTTPFetcher. First get the download URL for that file.

NSString *downloadedString = file.downloadUrl; // file is GTLDriveFile
GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadedString];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
{
     if (error == nil)
     {
         if(data != nil){
           // You have successfully downloaded the file write it with its name
           // NSString *name = file.title;
         }
     }
     else
     {
         NSLog(@"Error - %@", error.description)
     }
}];

Note: If you found "downloadedString" null Or empty just have look at file.JSON there are array of "exportsLinks" then you can get the file with one of them.

3. How to upload a file in specific folder: This is an example of uploading image.

-(void)uploadImage:(UIImage *)image
{
    // We need data to upload it so convert it into data
    // If you are getting your file from any path then use "dataWithContentsOfFile:" method
    NSData *data = UIImagePNGRepresentation(image);

    // define the mimeType
    NSString *mimeType = @"image/png";

    // This is just because of unique name you can give it whatever you want
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd-MMM-yyyy-hh-mm-ss"];
    NSString *fileName = [df stringFromDate:[NSDate date]];
    fileName = [fileName stringByAppendingPathExtension:@"png"];

    // Initialize newFile like this
    GTLDriveFile *newFile = [[GTLDriveFile alloc] init];
    newFile.mimeType = mimeType;
    newFile.originalFilename = fileName;
    newFile.title = fileName;

    // Query and UploadParameters
    GTLUploadParameters *uploadParameters = [GTLUploadParameters uploadParametersWithData:data MIMEType:mimeType];
    GTLQueryDrive *query = [GTLQueryDrive queryForFilesInsertWithObject:newFile uploadParameters:uploadParameters];

    // This is for uploading into specific folder, I set it "root" for root folder.
    // You can give any "folderIdentifier" to upload in that folder
    GTLDriveParentReference *parentReference = [GTLDriveParentReference object];
    parentReference.identifier = @"root";
    newFile.parents = @[parentReference];

    // And at last this is the method to upload the file
    [[self driveService] executeQuery:query completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {

        if (error){
            NSLog(@"Error: %@", error.description);
        }
        else{
            NSLog(@"File has been uploaded successfully in root folder.");
        }
    }];
}

这篇关于从Google云端硬盘列出所有文件夹内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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