I have a document-based iOS application with a UIDocument
subclass. I need to be able to move the file it represents on the file-system. I have considered moving it with an NSFileManager
, but this would mess up the UIDocument
's fileURL
property. Any ideas on how to solve this little conundrum?
This might be old but still relevant.
What you want to do is the following:
For moving: move your file using NSFileCoordinator, inside the coordinator's block, call
[fileCoordinator itemAtURL:URL willMoveToURL:toURL];
[fileManager moveItemAtURL:newURL toURL:toURL error:&moveError];
[fileCoordinator itemAtURL:URL didMoveToURL:toURL];
For deleting: overwrite your UIDocument subclass or implement the file presenter protocol method accommodatePresentedItemDeletionWithCompletionHandler:
to close the document.
- (void)accommodatePresentedItemDeletionWithCompletionHandler:(void (^)(NSError *))completionHandler;
{
[self closeWithCompletionHandler:^(BOOL success) {
NSError *err;
if (!success)
err = [NSError error]; // implement your error here if you want
completionHandler(err);
}];
}
Thus ensuring it will correctly handle being moved.
You can rename a UIDocument by first closing it, and then in the completion handler, moving the file using NSFileManager. Once the file has been successfully moved, initialize a new instance of your UIDocument subclass using the new file URL:
NSURL *directoryURL = [_document.fileURL URLByDeletingLastPathComponent];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *filePath = [directoryURL.path stringByAppendingPathComponent:@"NewFileName"];
[_document closeWithCompletionHandler:^(BOOL success) {
NSError *error;
if (success)
success = [fileManager moveItemAtPath:_document.fileURL.path toPath:filePath error:&error];
if (success) {
NSURL *url = [NSURL fileURLWithPath:filePath];
// I handle opening the document and updating the UI in setDocument:
self.document = [[MyDocumentSubclass alloc] initWithFileName:[url lastPathComponent] dateModified:[NSDate date] andURL:url];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Unable to rename document" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[alert show];
NSLog(@"Unable to move document: %@", error);
}
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With