Open local PDF file in iBooks - ios

I am trying to open a PDF file that I have stored locally within my app in iBooks. The app currently has a list of "literature" in a table view and when each cell is tapped the app segues to a webView that displays the PDF file (works great). I have made a BarButton at the top right in navBar to allow the user to open the PDF in iBooks (so they can store it on his/her device).
So far the button will open a UIDocumentInteractionController that displays all apps on the device that can open the file (after checking if iBooks is installed). Then when I click the iBooks icon the app crashes. I was able to revise the code so that iBooks opens without crashing, but the PDF file is not carried through so it's kind of pointless (code below is reverted back to when it crashes).
Code below is inside the IBAction of the barButton...
NSString *path = [[NSBundle mainBundle] pathForResource:litFileName ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:targetURL];
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:#"itms-bookss:"]])
{
[docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
NSLog(#"ibooks is installed");
}
else
{
NSLog(#"no ibooks installed");
}

Fixed it! Took some time away from the project and after coming back two weeks later I figured it out in <15 minutes.
So it was a memory issue for the docController and by declaring in the .h file and using (retain) it works perfectly. I was also able to use the [NSBundle mainBundle] method as well.
.h
#property (retain)UIDocumentInteractionController *docController;
.m
#synthesize docController;
//in bar button IBAction
NSString *path = [[NSBundle mainBundle] pathForResource:litFileName ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
docController = [UIDocumentInteractionController interactionControllerWithURL:targetURL];
if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:#"itms-books:"]]) {
[docController presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
NSLog(#"iBooks installed");
} else {
NSLog(#"iBooks not installed");
}

On iOS 8 the layout of the file system changed and sharing files directly from the main bundle no longer works. Copy the file to the documentsdirectory and share it from there.
Here is how to create the file path:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *fileName = [NSString stringWithFormat:#"%#.pdf",litFileName];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSURL *url = [NSURL fileURLWithPath:filePath];

Related

Open Instagram in IOS 9 with UIDocumentInteractionController

Hi this is my code to open Instagram App directly with an image. As stated in Apple document relative to UIDocumentInteractionController and in Instagram hook page this snippet of code should open instagram directly with the image, but in all testing conditions it open the action sheet with all the app compatible with the extension saved.
I've also whitelisted instagram in LSApplicationQueriesSchemes.
How can i achive this result? It's a bug or a new security feature of IOS 9?
Thanks in advance for your help
NSURL *instagramURL = [NSURL URLWithString:#"instagram:/"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.ig"];
[UIImagePNGRepresentation(capturedImage) writeToFile:getImagePath atomically:YES];
NSURL *imageFileURL =[NSURL fileURLWithPath:getImagePath];
NSLog(#"imag %#",imageFileURL);
self.dic.delegate = self;
self.dic.UTI = #"com.instagram.photo";
self.dic = [self setupControllerWithURL:imageFileURL usingDelegate:self];
[self.dic presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
} else //prompt for app missing
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL
usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
if you save the image as .igo the only apps i see in the actionsheet are "Instagram" "Notes" and "other.
edit: I have't found a way to open Instagram directly with an image it only seems possible to open it directly with
NSURL *instagramURL = [NSURL URLWithString:#"instagram://location?id=1"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
[[UIApplication sharedApplication] openURL:instagramURL];
}
but you can't add an image with that
edit2: I forgot to add that for the .igo format you need to use self.dic.UTI = "com.instagram.exclusivegram"

iOS9 - Sharing to Instagram (w/ hooks) not working

I'm currently updating one of my apps to be iOS9 compatible, and I'm having trouble with the share to Instagram function. I'm using the Instagram hooks as stated on their developer site: (https://instagram.com/developer/mobile-sharing/iphone-hooks/)
The image I wish to share is being generated successfully, with the .igo suffix, and the functionality is still working as intended on iOS8. It just seems to have broken with the new version of iOS.
Here's the code for sharing to Instagram, using the UIDocumentInteractionController:
NSURL *instagramURL = [NSURL URLWithString:#"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
//convert image into .png format.
NSData *imageData = UIImagePNGRepresentation(image);
//create instance of NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
//add our image to the path
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"insta.igo"]];
//finally save the path (image)
[fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
CGRect rect = CGRectMake(0 ,0 , 0, 0);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSString *fileNameToSave = [NSString stringWithFormat:#"Documents/insta.igo"];
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:fileNameToSave];
NSLog(#"jpg path %#",jpgPath);
NSString *newJpgPath = [NSString stringWithFormat:#"file://%#",jpgPath];
NSLog(#"with File path %#",newJpgPath);
NSURL *igImageHookFile = [[NSURL alloc]initFileURLWithPath:newJpgPath];
NSLog(#"url Path %#",igImageHookFile);
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.documentController setDelegate:self];
[self.documentController setUTI:#"com.instagram.exclusivegram"];
[self.documentController presentOpenInMenuFromRect:rect inView:self.view animated:YES];
} else {
NSLog (#"Instagram not found");
}
It's probably worth mentioning I've already configured the URL schemes in the info.plist as required with the iOS9 changes.
The UIDocumentInteractionController does appear, and has the option 'Copy to Instagram'. Pressing this option just leads to the controller being dismissed, with no log messages or breakpoints being called on the controller's delegate (set to self; the view controller).
If anyone has, or has had trouble with this, it would be great to hear your thoughts, or better yet, how it was solved.
Update
It's also worth mentioning, on an iOS8 device, the Document Interaction Controller shows an 'Open in Instagram' button. The iOS9 device shows a 'Copy to Instagram' button.
After changing this line of code:
NSURL *igImageHookFile = [[NSURL alloc] initFileURLWithPath:newJpgPath];
to this:
NSURL *igImageHookFile = [NSURL URLWithString:newJpgPath];
The Instagram-share function for iOS 9 is now working. It seems that the previous line of code, converting the NSString to an NSURL would place "--://file" at the end of the URL path, which doesn't seem to register well with iOS 9. Simply converting the NSString to NSURL without initialising as a file URL seems to work.
You have to add a new key to your Info.plist file; it's an iOS 9 change for URL schemes. Check out the first answer for this question: iOS 9 not opening Instagram app with URL SCHEME. And just FYI, iOS 9 changes the "Open in Instagram" title for the UIDocumentInteractionController to "Copy to Instagram." Not sure why.

How to get device's pdfs and other files in iOS app?

I want to import data from my iPhone to my application . up till now i have successfully imported Photo Library and music , but i also want to import pdf and other documents in my iOS app? How can i do that?
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSFileManager *mgr = [[NSFileManager alloc] init];
NSArray *allFiles = [mgr contentsOfDirectoryAtPath:bundlePath error:NULL];
for (NSString *fileName in allFiles)
{
if ([[fileName pathExtension] isEqualToString:#"pdf"])
{
NSString *fullFilePath = [bundlePath stringByAppendingPathComponent:fileName];
// fullFilePath now contains the path to your pdf file
// DoSomethingWithFile(fullFilePath);
NSLog(#"file: %#",fullFilePath);
}
}
NSURL *url = [[NSBundle mainBundle] URLForResource:#"" withExtension: #"pdf"];
NSLog(#"File: %#",url);
You can't do it in iOS 8 (I haven't checked 9 though). You can't even enlist your app (adding corresponding URL schemes) in the sharing menu of iBooks.
You have to associate your app with the PDF types which you want to open. You can do this by adding some parameters to your Info.plist.
There's a well-answered post which explains this:
How do I associate file types with an iPhone application?
You should also consider reading Apple's documentation and a blog post written by me.

Load .ics file to add calendar event from application

To load .ics file from url I am using open url method as below
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:fullURL]];
It's working fine.
But I want to load .ics file from application's bundle without URL. eg., I have file is test.ics file How can I load this file, can we load anyway it without URL?
You can load the ics file locally
NSURL *path = [[NSBundle mainBundle] URLForResource:#'icsName' withExtension:#'ics'];
[[UIApplication sharedApplication] openURL:path];
- (IBAction)displayICS:(id)sender
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"ics"];
NSURL *url = [NSURL fileURLWithPath:path];
UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:url];
dc.delegate = self;
[dc presentPreviewAnimated:YES];
}
-(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
return self;
}

iOS 6 - Able to save .pdf from URL, able to display it in a WebView, NOT able to move it to iBooks

This is what I'm trying to do:
Get a .pdf from external URL
Save it into my local disk
Display it in a WebView
Allow the user to move the .pdf to another app who can read .pdf
Everything from 1 to 3 works fine. But nothing is moved/shared to/with other apps. I can't understand what I'm doing wrong. This is what I'm doing.
How I save the pdf in the Documents folder (viewDidLoad):
// to save the pdf into local file system (tempString is the pdf url)
NSData *pdfData = [[NSData alloc]
initWithContentsOfURL:[NSURL URLWithString:tempString]];
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePAth atomically:YES];
// to populate the WebView
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url2];
[my_web_view setUserInteractionEnabled:YES];
//[editoriale_view setDelegate:self];
[my_web_view loadRequest:requestObj];
In my viewDidLoad() function I create a button to allow the user to open a list of apps who can read .pdf files:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self
action:#selector(show_Button)];
And here's my show_Button function:
-(void)show_Button {
NSString *resourceToPath = [[NSString alloc]
initWithString:[[[[NSBundle mainBundle] resourcePath]
stringByDeletingLastPathComponent]
stringByAppendingPathComponent:#"Documents"]];
NSString *filePAth = [resourceToPath
stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
When I try this on my device everything works fine until I tap on one of the icons in the list (i.e. the iBooks one). Then the app closes (it doesn't crash, it simply closes).
Here's what the console prints for the two logs I put in the show_Button function:
1. filePath = /Users/[MY_USER]/Library/Application Support/iPhone
Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
2. url2 = file://localhost/Users/[MY_USER]/Library/Application%20Support/
iPhone%20Simulator/6.1/Applications/[MY_EXAD_APP_ID]/Documents/myPDF.pdf
Anyone wants to try to make me understand what I'm doing wrong? I'm using Xcode 4.6. I browsed my iPhone app file system with a third-party software and the file "MyPDF.pdf" actually IS in the Documents" folder, and that's clear because the WebView is correctly populated.
Change CGRectZero to self.view.bounds when you display the document controller.
Solved. I had not implemented the UIDocumentenInteractionController delegate in the .h file. Now I have and everything works fine. Thank you to #trojanfoe for the useful hint.

Resources