Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to move a UIDocument to a new location on the file-system

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?

like image 207
agentfll Avatar asked Nov 27 '11 07:11

agentfll


2 Answers

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.

like image 187
Elland Avatar answered Nov 16 '22 08:11

Elland


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);
    }
}];
like image 4
Justin Driscoll Avatar answered Nov 16 '22 09:11

Justin Driscoll