【问题标题】:Listing All Folder content from Google Drive列出 Google Drive 中的所有文件夹内容
【发布时间】:2014-02-13 21:26:37
【问题描述】:

您好,我已使用 Dr. Edit 谷歌驱动器中的示例代码将 google Dive 与我的应用程序集成。但我无法查看存储在我的 Google Drive 帐户中的所有文件。

//这个我试过了

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

//我要显示NSLog中的所有内容...

【问题讨论】:

    标签: iphone ios objective-c google-drive-api


    【解决方案1】:

    1.如何从 Google 云端硬盘获取所有文件。

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

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

    这里是所有方法的定义:

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

    注意:要获得完整的驱动器访问权限,您的范围应为 kGTLAuthScopeDrive

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

    2。如何下载特定文件。

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

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

    注意:如果您发现“downloadedString”为空或为空,只需查看 file.JSON,其中有“exportsLinks”数组,然后您可以使用其中之一获取文件。

    3.如何上传特定文件夹中的文件:这是上传图片的示例。

    -(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.");
            }
        }];
    }
    

    【讨论】:

    • 您登录成功了吗?如果是,那么它应该可以工作。还要检查您应用的客户端和密钥。
    • 我能够成功登录.. 并且客户端 ID 和机密 ID 是正确的.. 那就是我能够登录...但没有得到任何东西
    • @JamesRyan - 我认为你需要一个完整的描述。我已经给了,请现在检查。
    • 您好,我可以列出文件夹名称,但不能列出各种文件夹的内容...如何列出属于扩展 mp3、mp4、mkv 和 mov 等的内容
    • 请帮助我,我只想列出来自谷歌驱动器的 mp3、mp4、mov、mov、avi 类型的文件...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多