【问题标题】:Open local PDF file in iBooks在 iBooks 中打开本地 PDF 文件
【发布时间】:2014-12-08 05:17:30
【问题描述】:

我正在尝试在 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");
}

【问题讨论】:

    标签: ios objective-c pdf ios8 ibooks


    【解决方案1】:

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

    创建文件路径的方法如下:

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

    【讨论】:

    • 不确定该怎么做...我试过: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingString:[NSString stringWithFormat:@"%@.pdf",litFileName]]; NSURL *url = [NSURL fileURLWithPath:filePath];同样的错误
    • 您将文件错误地添加到路径中,您应该使用stringByAppendingPathComponent: 而不仅仅是附加字符串
    【解决方案2】:

    修好了!花了一些时间离开这个项目,两周后我回来后不到 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");
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多