We have a code to download a PDF from the server using a SOAP protocol.
We store the file on the Documents folder of the iOs device, and the we want to allow the user to open the file (usually PDF's files)
But, at least on the simulator, the application didn't open the file successfully.
Of course, I can open manually the file (in order to check that the file has been downloaded perfectly)
// Get the documents folder where write the content
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:documentDownloaded.fileName];
if ([[NSFileManager defaultManager] fileExistsAtPath:[self getFileCompletePath]]){
NSString *filePath = [[NSString alloc] initWithFormat:#"%#", [self getFileCompletePath]];
NSURL *url = [[NSURL alloc] initFileURLWithPath:filePath];
if ([[UIApplication sharedApplication] canOpenURL:url]){
[[UIApplication sharedApplication] openURL: url];
} else {
NSLog(#"Not supported application to open the file %#", filePath);
}
[url release];
[filePath release];
}
The file full path in the simulator is:
/Users/User/Library/Application Support/iPhone Simulator/4.3.2/Applications/87800296-2917-4F26-B864-B20069336D1D/Documents/0000907.pdf
Anybody knows if is something wrong?
The file could be and spreadsheet, pdf, image, document ... but for the first work around will be great just for pdf's.
Thank you,
omz you was right. The final solution was the next.
My controller implemented the UIDocumentInteractionControllerDelegate
When the user wants to open the document the code was the next:
NSString *filePath = [[NSString alloc] initWithFormat:#"%#", [self getFileCompletePath]];
NSURL *url = [[NSURL alloc] initFileURLWithPath:filePath];
UIDocumentInteractionController *documentController = [self setupControllerWithURL:url
usingDelegate:self];
[documentController retain];
[documentController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
[url release];
[filePath release];
Using the next method, you could found it on the apple developer library
- (UIDocumentInteractionController *)
setupControllerWithURL: (NSURL *) fileURL
usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
Finally we include the delegate methods:
#pragma mark methods for the UIDocumentInteractionControllerDelegate
- (void)previewDocumentWithURL:(NSURL*)url
{
UIDocumentInteractionController* preview = [UIDocumentInteractionController interactionControllerWithURL:url];
preview.delegate = self;
[preview presentPreviewAnimated:YES];
[preview retain];
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller
{
[controller autorelease];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
return self;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller{
return self.view.frame;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
return self.view;
}
Thank you,
You cannot open file URLs with UIApplication's openURL: method. Because of sandboxing, other apps could not access any files within your application's Documents folder.
You need to use UIDocumentInteractionController to open documents that you download or create in other applications.
Related
I have gone through many links, but nothing worked for me. All i need to do is fetch all iCloud Drive files and download images. I succeeded fetching all files using below code
- (void)presentDocumentPicker {
NSArray *documentTypes = #[#"public.content", #"public.text", #"public.source-code ", #"public.image", #"public.audiovisual-content", #"com.adobe.pdf", #"com.apple.keynote.key", #"com.microsoft.word.doc", #"com.microsoft.excel.xls", #"com.microsoft.powerpoint.ppt"];
UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
documentPickerViewController.delegate = self;
[self presentViewController:documentPickerViewController animated:YES completion:nil];
}
#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
self.documentURL = url;
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.delegate = self;
previewController.dataSource = self;
[self.navigationController pushViewController:previewController animated:YES];
}
now i don't know how to proceed further to download image.
i was able to download images using this
#pragma mark - UIDocumentPickerDelegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
self.documentURL = url;
NSNumber *isDownloadedValue = NULL;
BOOL success = [url getResourceValue:&isDownloadedValue forKey: NSURLUbiquitousItemIsDownloadingKey error:NULL];
if (success && ![isDownloadedValue boolValue]) {
[[NSFileManager defaultManager]startDownloadingUbiquitousItemAtURL:url error:nil];
// load image from Ubiquity Documents directory
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage * image = [UIImage imageWithData:imageData];
}
QLPreviewController *previewController = [[QLPreviewController alloc] init];
previewController.delegate = self;
previewController.dataSource = self;
[self.navigationController pushViewController:previewController animated:YES];
}
In previous iOS, I used this code and UIDocumentInteractionController to open a file, from my app, with another app. Since iOS 9, the UIDocumentInteractionController appears on the screen, I select the option "Copy to", but nothing happens. How can I solve this?
NSURL *URL = [NSURL fileURLWithPath:path];
if (URL != nil) {
// Initialize Document Interaction Controller
documentController = [UIDocumentInteractionController interactionControllerWithURL:URL];
documentController.delegate = self;
[documentController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
you have to manage your response time of open :-
-(void)exportToDropBox{
[self performSelector:#selector(presentImagePicker) withObject:nil afterDelay:1.0];
}
-(void)presentImagePicker{
NSURL *targetURL = [NSURL fileURLWithPath:exportedPdfFileName];
[self presentDocumentWithURL2:targetURL];
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
return self;
}
- (void)presentDocumentWithURL2:(NSURL*)url {
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
self.documentController.delegate = self;
[self.documentController presentOpenInMenuFromRect:CGRectMake(self.view.frame.size.width/2 - 49/2, self.view.frame.size.height-49, 49, 49) inView:self.view animated:YES];
}
- (void)documentInteractionControllerDidEndPreview:(UIDocumentInteractionController *)controller {
self.documentController = nil;
}
I am using UIDocumentInteractionController for opening documents in my app. I have used method below for previewing the PDF file:-
- (IBAction)previewDocument:(id)sender
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"pdf"];
// Initialize Document Interaction Controller
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
// Configure Document Interaction Controller
[self.documentInteractionController setDelegate:self];
// Preview PDF
[self.documentInteractionController presentOptionsMenuFromRect:down.frame inView:self.view animated:YES];
}
I have read that we can read files in an app from other app too by UIDocumentInteractionController.
In my app, How can I read the files from other app using UIDocumentInteractionController? How does all this happens?
Previewing the PDF document and sharing.
Set Delegate Method:-
UIDocumentInteractionControllerDelegate
NSURL *URL = [[NSBundle mainBundle] URLForResource:#"Your PDF Name" withExtension:#"pdf"];
UIDocumentInteractionController *documentInteractionController =[UIDocumentInteractionController interactionControllerWithURL:URL];
documentInteractionController.delegate = self;
[documentInteractionController presentPreviewAnimated:YES];
- (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller {
return self;
}
If you have any confusion, click on the below link and read :
https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/DocumentInteraction_TopicsForIOS/Articles/PreviewingandOpeningItems.html
I am showing a local html file on my UiWebView using following code.
NSString *path = [[NSBundle mainBundle] pathForResource:#"test.html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];
[_webView loadHTMLString:htmlString baseURL:baseURL];
[_webView setBackgroundColor:[UIColor clearColor]];
App is showing the html correctly. In the test.html there is a link to local pdf file hello.pdf. This pdf is added to the project. But when I click on the link nothing happens. I want to load pdf on my web view when user clicks on the link.
I want to use the UIWebView delegate to send requests for internet hyperlinks (e.g. http://www.google.com) to the safari app.
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType
{
NSLog(#"%#",inRequest.URL.absoluteString);
if([inRequest.URL.absoluteString rangeOfString:#"hello.pdf"].location == NSNotFound)
{
if ( inType == UIWebViewNavigationTypeLinkClicked )
{
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
return YES;
}
else
{
return NO;
}
}
You should have stated more clearly that you wanted internet hyperlinks to load in Safari and local hyperlinks to load in your UIWebView.
I've just tested this and it does what you want:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType
{
if (inType == UIWebViewNavigationTypeLinkClicked) {
if ([inRequest.URL.absoluteString rangeOfString:#"http://"].location == NSNotFound) {
return YES;
}
else {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
}
else {
return YES;
}
}
This works by only loading links in your UIWebView that don't contain the hyper text type protocol prefix (http://).
Tip: Make sure you've set the delegate for the UIWebView in the viewDidLoad method.
- (void)viewDidLoad
{
[super viewDidLoad];
webView.delegate = self;
}
SOLVED (Thanks Regexident)
I have an app that passes the file path of a PDF to a custom -(id)init init method. It is added to the table and when it is selected, it calls the else statement for a non existent file:
- (void) gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index {
NSLog (#"Selected theArgument=%d\n", index);
UIViewController *viewController = [[[UIViewController alloc]init]autorelease];
{
//if file is built-in, read from the bundle
if (index <= 3)
{
// first section is our build-in documents
NSString *fileURLs = [_documentIconsURLs objectAtIndex:index];
NSLog(#"file url -%#", fileURLs);
viewController = [[[xSheetMusicViewController alloc]initWithContentURL:fileURLs]autorelease];
}
//if file is external, read from URL
else
{
// second section is the contents of the Documents folder
NSString *fileURL = [_documentIconsURLs objectAtIndex:index];
NSLog(#"file url -%#", fileURL);
NSString *path;
NSString *documentsDirectoryPath = [self applicationDocumentsDirectory];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileURL];
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryPath])
{
viewController = [[[xSheetMusicViewController alloc]initWithDocumentURL:fileURL]autorelease];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Failure!" message:#"The Selected File Does Not Exist"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
return;
}
}
[self.navigationController setNavigationBarHidden:YES animated:NO];
[UIView beginAnimations:#"animation" context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:YES];
[self.navigationController pushViewController:viewController animated:NO];
[UIView commitAnimations];
}
}
So whenever I have a document with no space in it's name, it pushes and inits. But when the file name has a space in it, it says it does not exist. And when I remove the if-else method, it init's, but crashes because the file doesn't exist. I've tried to replace the %20 in the file path with a regular space, but the method continues to call the else part.
So, is the file path not standardized and readable, or is my else method wrong?
As your path appears to be a percentage escaped path string I'd try this:
[fileURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
And I'd rename fileURL to fileURLString to make clear that it's an NSString containing a URL path, not an actual NSURL (which your variable name would falsely imply).
But I'd check the code that populates _documentIconsURLs, as it's probabaly the origin of your problem.