我试图在 UIWebview
中显示 pdf,但出现错误。谁能帮我解释为什么这不起作用?错误是:
* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[NSURL initFileURLWithPath:]:nil 字符串参数”
每个字符串都是正确的,除了 path ,它的长度似乎为 0,我不知道为什么。
NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [docPath objectAtIndex:0];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 700, 500)];
NSString *path = [[NSBundle mainBundle] pathForResource:@"pdfDoc" ofType:@"pdf" inDirectory:documentDirectory];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
最佳答案
你不能这样做:
NSString *path = [[NSBundle mainBundle] pathForResource:@"pdfDoc" ofType:@"pdf" inDirectory:documentDirectory];
因为 NSBundle
只能获取包中文件的路径,而不能获取文档目录中的文件路径(因此它返回 nil
并且您会收到错误)。
如果文件位于 bundle 中,则仅按名称搜索它。如果文件位于文档文件夹中,请获取该文件夹的路径并附加名称 (stringByAppendingPathComponent:
)。然后使用该路径创建文件 URL。
关于ios - 在 UIWebview 中打开 pdf 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21385539/