werbary werbary - 1 year ago 112
iOS Question

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download