将iCloud集成到ios App并从iCloud中检索文件

时间:2016-05-04 11:04:57

标签: ios icloud icloud-api icloud-drive

我使用raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1

将iCloud集成到iOS应用程序中

但我无法将iCloud中的所有文件显示到我们的iOS应用程序中,还需要特定类型的文件,如pdf,doc和docx

任何人都可以建议我。

2 个答案:

答案 0 :(得分:1)

请遵循本指南

https://www.raywenderlich.com/12779/icloud-and-uidocument-beyond-the-basics-part-1

下载示例代码

https://github.com/rwenderlich/PhotoKeeper

检查iCloud是否可用

- (void)initializeiCloudAccessWithCompletion:(void (^)(BOOL available)) completion {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        _iCloudRoot = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
        if (_iCloudRoot != nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"iCloud available at: %@", _iCloudRoot);
                completion(TRUE);
            });            
        }            
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"iCloud not available");
                completion(FALSE);
            });
        }
    });
}

查询pdf,doc和docx等苍蝇的类型

- (NSMetadataQuery *)documentQuery {

    NSMetadataQuery * query = [[NSMetadataQuery alloc] init];
    if (query) {

        // Search documents subdir only
        [query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];

        // Add a predicate for finding the documents
        NSString * filePattern = [NSString stringWithFormat:@"*.%@", PTK_EXTENSION];
        [query setPredicate:[NSPredicate predicateWithFormat:@"%K LIKE %@",
                             NSMetadataItemFSNameKey, filePattern]];        

    }
    return query;

}

答案 1 :(得分:1)

按照以下步骤将iCloud集成到iOS应用中并检索文件。 1.从您的开发者帐户启用iCloud。 2.在开发者帐户中创建iCloud容器权利。 3.然后使用下面的代码来集成您的iCloud集成。

首先导入 #import 并添加 iCloudDelegate 委托,然后设置委托:

                // Setup iCloud
            [[iCloud sharedCloud] setDelegate:self];
            [[iCloud sharedCloud] setVerboseLogging:YES];
            [[iCloud sharedCloud] setupiCloudDocumentSyncWithUbiquityContainer:nil];

            [self showiCloudFiles];

然后在

下面实施方法 showiCloudFiles
-(void) showiCloudFiles{

BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:@"userCloudPref"] == YES) {
    UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.content"]
                                                                                                            inMode:UIDocumentPickerModeImport];
    documentPicker.delegate = self;
    documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:documentPicker animated:YES completion:nil];

}
else if ([[NSUserDefaults standardUserDefaults] boolForKey:@"userCloudPref"] == NO) {

    UIAlertController * alert = SIMPLE_ALERT_VIEW(@"iCloud Disabled", @"You have disabled iCloud for this app. Would you like to turn it on again?");
    UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];
    UIAlertAction* deleteButton = [UIAlertAction actionWithTitle:@"Turn On iCloud"
                                                           style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action){
                                                             [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"userCloudPref"];
                                                             [[NSUserDefaults standardUserDefaults] synchronize];

                                                             BOOL cloudAvailable = [[iCloud sharedCloud] checkCloudAvailability];
                                                             if (cloudAvailable && [[NSUserDefaults standardUserDefaults] boolForKey:@"userCloudPref"] == YES) {
                                                                 UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:@[@"public.content"]
                                                                                                                                                                         inMode:UIDocumentPickerModeImport];
                                                                 documentPicker.delegate = self;
                                                                 documentPicker.modalPresentationStyle = UIModalPresentationFormSheet;
                                                                 [self presentViewController:documentPicker animated:YES completion:nil];

                                                             }
                                                         }];
    [alert addAction:deleteButton];
    [self presentViewController:alert animated:YES completion:nil];

} else {

    UIAlertController * alert = SIMPLE_ALERT_VIEW(@"Setup iCloud", @"iCloud is not available. Sign into an iCloud account on this device and check that this app has valid entitlements.");
    UIAlertAction* cancelButton = [UIAlertAction actionWithTitle:@"Okay" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];[alert addAction:cancelButton];                                                                
                                                         }];
    [self presentViewController:alert animated:YES completion:nil];

}

}

之后下载文件使用UIDocumentPickerDelegate方法:

 #pragma mark - UIDocumentPickerDelegate
-(void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url{
if (controller.documentPickerMode == UIDocumentPickerModeImport) {
    //NSLog(@"%@",url);


    [url startAccessingSecurityScopedResource];
    NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] init];
    NSError *error;
    __block NSData *fileData;

    [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
// File name for use in writing the file out later
NSString *fileName = [newURL lastPathComponent]; NSString *fileExtension = [newURL pathExtension]; if([fileExtension isEqualToString:@"zip"]) {if([[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:@"pages"] ||
      [[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:@"numbers"] ||
      [[[newURL URLByDeletingPathExtension] pathExtension] isEqualToString:@"key"] ) {
       // Remove .zip if it is an iWork file
       fileExtension = [[newURL URLByDeletingPathExtension] pathExtension];
       fileName = [[newURL URLByDeletingPathExtension] lastPathComponent];
}
} 
NSError *fileConversionError;fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingUncached error:&fileConversionError];
        // Do further code using  fileData
        }
    }];
[url stopAccessingSecurityScopedResource];
    }
}

对于 UIDocumentPicker ,请访问此链接iOS-8-UIDocumentPicker