Open local PDF file in iBooks

2020-08-02 00:59发布

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");
}

2条回答
闹够了就滚
2楼-- · 2020-08-02 01:19

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];
查看更多
Fickle 薄情
3楼-- · 2020-08-02 01:30

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");

}
查看更多
登录 后发表回答