简体   繁体   中英

Integrate iCloud into ios App and Retrieve files from iCloud

I integrated iCloud into iOS app using raywenderlich https://www.raywenderlich.com/6015/beginning-icloud-in-ios-5-tutorial-part-1

But iam unable to show all the files from iCloud to our iOS app and also need specific type of files like pdf, doc and docx

Can any one suggest me.

Follow this guide

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

Download sample code at

https://github.com/rwenderlich/PhotoKeeper

Check if iCloud available

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

Query type of flies like pdf, doc and 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;

}

Follow below steps to integrate iCloud in iOS app and retrieve files. 1. Enable iCloud from your developer account. 2. Create iCloud containers entitlement at developer account. 3. Then just use below code where you want to integrate your iCloud integration.

First of all import #import and add iCloudDelegate delegate then set delegate:

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

            [self showiCloudFiles];

then implementation of method showiCloudFiles below

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

}

}

After that for downloading file use UIDocumentPickerDelegate method:

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

For UIDocumentPicker visit this link iOS-8-UIDocumentPicker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM