Objective-C中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 (likehttps://example.com) or properly formatted string-based URLs. For local files, you needfileURLWithPath: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:
- Go to your target's
Build Phasestab - Expand
Copy Bundle Resources - Verify
Sample1.pdfis listed there (if not, drag it into this list)
内容的提问来源于stack exchange,提问作者jeddi

