You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C中WKWebView加载PDF显示空白及报错问题求助

解决WKWebView加载PDF时的空白页面与编码错误问题

Hey there, let's break down why your code is throwing that encoding error and showing a blank page, then fix it up properly.

First, the core issue: you're trying to read a binary PDF file as if it's UTF-8 encoded plain text. PDFs aren't text files—they contain binary data like fonts, images, and structured layout info—so stringWithContentsOfFile:encoding:error: will always fail here, hence the NSCocoaErrorDomain Code=261 error. On top of that, even if you did get some garbage string out of that call, using URLWithString: on it is totally wrong for loading local files.

Correct Objective-C Implementation

Skip the text reading entirely and load the PDF directly via its file URL:

// Get the path to your PDF in the main bundle
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Sample1" ofType:@"pdf"];

if (filePath) {
    // Convert the file path to a proper file URL (this is the key fix!)
    NSURL *pdfFileURL = [NSURL fileURLWithPath:filePath];
    
    // Set up WKWebView configuration and instance
    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:webConfig];
    webView.backgroundColor = [UIColor whiteColor];
    
    // Load the PDF using the file URL (better than loadRequest for local files)
    [webView loadFileURL:pdfFileURL allowingReadAccessToURL:[pdfFileURL URLByDeletingLastPathComponent]];
    
    [self.view addSubview:webView];
} else {
    NSLog(@"Oops! Couldn't find Sample1.pdf in your main bundle. Double-check the filename and that it's added to your project.");
}

Why Your Original Code Failed

  • Mistake 1: Reading binary data as text
    stringWithContentsOfFile:encoding:error: is designed for plain text files (like .txt or .json). PDFs are binary, so this method can't parse them correctly, leading to the encoding error.
  • Mistake 2: Invalid URL creation
    URLWithString: is for parsing web URLs (like https://example.com) or properly formatted string-based URLs. For local files, you need fileURLWithPath: to convert the filesystem path into a valid NSURL that WKWebView can understand.

Quick Check to Avoid Future Headaches

Make sure Sample1.pdf is actually added to your Xcode project:

  1. Go to your target's Build Phases tab
  2. Expand Copy Bundle Resources
  3. Verify Sample1.pdf is listed there (if not, drag it into this list)

内容的提问来源于stack exchange,提问作者jeddi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:42:51