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
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;
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.
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