Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIDocumentInteractionController and file from web

I want to open file from the web in other apps.

My code:

NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *resp, NSData *respData, NSError *error){
    NSLog(@"resp data length: %i", respData.length);
    NSArray *names = [objDict[@"name"] componentsSeparatedByString:@"."];
    NSString *fileName = [@"downloaded." stringByAppendingString:names[names.count-1]];
    NSString * path = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
    NSError *errorC = nil;
    BOOL success = [respData writeToFile:path 
                 options:NSDataWritingFileProtectionComplete
                   error:&errorC];

    if (success) {
        UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path]];
        documentController.delegate = self;
        [documentController presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
    } else {
        NSLog(@"fail: %@", errorC.description);
    }
}];

It shows panel, but crashes on click of any button (not 'Cancel' only).

I enabled zombie objects and it writes:

-[UIDocumentInteractionController URL]: message sent to deallocated instance
like image 350
werbary Avatar asked Feb 26 '13 19:02

werbary


2 Answers

I had a similar problem, but I was not initializing my UIDocumentInteractionController inside a block. I solved this using a property in my interface file so that the class would hold onto the instance of UIDocumentInteractionController strongly.

@property (nonatomic, strong) UIDocumentInteractionController *documentController;
like image 72
Eliot Arntz Avatar answered Oct 20 '22 02:10

Eliot Arntz


Take your UIDocumentInteractionController out of the NSURLConnection sendAsynchronousRequest block.

The document interaction controller has to stay around long after the connection is complete, but it is scoped to the block. After the block finishes, there will be no reference to it and it will get deallocated.

like image 25
DBD Avatar answered Oct 20 '22 00:10

DBD