How to delete iCloud documents?

2019-05-02 07:21发布

问题:

I'm using a UIDocument with iCloud. I'm not using CoreData. What's the best way to delete a UIDocument?

回答1:

To delete the document from iCloud, first you have to get the filename you want to delete. and then you can delete it using NSFileManager.

NSString *saveFileName = @"Report.pdf";
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSURL *ubiquitousPackage = [[ubiq URLByAppendingPathComponent:@"Documents"] URLByAppendingPathComponent:saveFileName];
NSFileManager *filemgr = [NSFileManager defaultManager];
[filemgr removeItemAtURL:ubiquitousPackage error:nil];

This is the way, which i used to delete document, Check it out. It is woking great for me. Thanks



回答2:

Copied from the "Deleting a Document" section of the Document-Based App Programming Guide for iOS.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    NSFileCoordinator* fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
    [fileCoordinator coordinateWritingItemAtURL:fileURL options:NSFileCoordinatorWritingForDeleting
        error:nil byAccessor:^(NSURL* writingURL) {
        NSFileManager* fileManager = [[NSFileManager alloc] init];
        [fileManager removeItemAtURL:writingURL error:nil];
    }];
});

N.B.: "When you delete a document from storage, your code should approximate what UIDocument does for reading and writing operations. It should perform the deletion asynchronously on a background queue, and it should use file coordination."



回答3:

SWIFT 3 come from @AlexChaffee 's answer

func deleteZipFile(with filePath: String) {
    DispatchQueue.global(qos: .default).async {
        let fileCoordinator = NSFileCoordinator(filePresenter: nil)
        fileCoordinator.coordinate(writingItemAt: URL(fileURLWithPath: filePath), options: NSFileCoordinator.WritingOptions.forDeleting, error: nil) {
            writingURL in
            do {
                try FileManager.default.removeItem(at: writingURL)
            } catch {
                DLog("error: \(error.localizedDescription)")
            }
        }
    }
}


回答4:

I think I found a solution:

[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:url destinationURL:nil error:nil]

Source: http://oleb.net/blog/2011/11/ios5-tech-talk-michael-jurewitz-on-icloud-storage/



回答5:

See Apple documentation of "Managing the Life-Cyle of a Document" under 'Deleting a Document."