首页 > 解决方案 > 无法使用 CGPDFDocumentCreateWithURL 读取 PDF 文档

问题描述

我尝试在 iOS 上加载 PDF 失败,但在调试代码时文档显示“0x0”作为值。

NSString *appFolderPath = [[NSBundle mainBundle] resourcePath];
NSString *pdfPath = [appFolderPath stringByAppendingString:@"/Data/Raw/test.pdf"];
    
CFStringRef cfsPath = (__bridge CFStringRef)pdfPath;

CFURLRef url = CFURLCreateWithFileSystemPath(NULL, cfsPath, kCFURLPOSIXPathStyle, 0);
    
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL(url);

这个片段可能有什么问题?我对 iOS 原生开发和 Objective-C 没有太多经验。

标签: iosobjective-cxcodeios-pdfkit

解决方案


首先检查文件是否存在于应用程序包中的给定位置。

强烈推荐使用 URL 相关的 APINSBundle

NSURL *appFolderURL = [[NSBundle mainBundle] resourceURL];
NSURL *pdfURL = [appFolderURL URLByAppendingPathComponent:@"Data/Raw/test.pdf"];

并使用更方便PDFDocument的 PDFKit 类而不是 CoreFoundation API

@import PDFKit;

PDFDocument *document = [[PDFDocument alloc] initWithURL:pdfURL];

推荐阅读