在iBooks中打开本地PDF文件

时间:2014-10-13 15:21:01

标签: ios objective-c pdf ios8 ibooks

我正在尝试打开我在iBooks中的应用程序中本地存储的PDF文件。该应用程序当前在表格视图中有一个“文献”列表,当点击每个单元格时,该应用程序将转换为显示PDF文件的webView(效果很好)。我在navBar的右上角创建了一个BarButton,允许用户在iBooks中打开PDF(这样他们就可以将它存储在他/她的设备上)。

到目前为止,按钮将打开UIDocumentInteractionController,显示设备上可以打开文件的所有应用程序(检查iBooks是否已安装)。然后当我点击iBooks图标时,应用程序崩溃了。我能够修改代码以便iBooks打开而不会崩溃,但PDF文件没有被执行所以它有点毫无意义(下面的代码恢复到它崩溃的时候)。

以下代码位于barButton的IBAction内......

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 个答案:

答案 0 :(得分:3)

修正了它!花了一些时间远离这个项目,两周后回来后,我在<15分钟内发现了它。

因此,对于docController来说,这是一个内存问题,通过在.h文件中声明并使用(保留)它可以完美地工作。我也能够使用[NSBundle mainBundle]方法。

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

}

答案 1 :(得分:1)

在iOS 8上,文件系统的布局发生了变化,直接从主包中共享文件不再有效。将文件复制到documentsdirectory并从那里共享。

以下是创建文件路径的方法:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *fileName = [NSString stringWithFormat:@"%@.pdf",litFileName];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSURL *url = [NSURL fileURLWithPath:filePath];