1

我在使用 WKWebView 和目标 c 可视化 pdf 文件的内容时遇到了麻烦。抱歉,我不熟悉 Swift。这是代码,但它显示一个空白页并返回以下错误:

错误域 = NSCocoaErrorDomain 代码 = 261 “无法使用文本编码 Unicode (UTF-8) 打开文件“Sample1.pdf”。

NSString *filePath;
filePath = [[NSBundle mainBundle] pathForResource:@"Sample1" ofType:@"pdf"];

NSString *TextToBeDisplayed;
NSError *err = nil;
TextToBeDisplayed = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];

if (TextToBeDisplayed == nil)
{
    NSLog(@"Case 1");
    NSLog(@"Error reading %@: %@", filePath, err);
}
else
{
    NSLog(@"Case 2");
    NSLog(@"File found");
}

if(TextToBeDisplayed != nil || [TextToBeDisplayed isEqualToString:@""])
{
    NSLog(@"Case 3");

    WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
    NSURLRequest *nsrequest=[NSURLRequest requestWithURL:[NSURL URLWithString:TextToBeDisplayed]];

    [webView setBackgroundColor:[UIColor whiteColor]];

    [webView loadRequest:nsrequest];
    [self.view addSubview:webView];
    //[InstructionsTextView addSubview:webView];
}
else
{
    NSLog(@"Case 4");
    NSLog(@"Error");
    //Error Domain=NSCocoaErrorDomain Code=261 "The file “Sample1.pdf” couldn’t be opened using text encoding Unicode (UTF-8).
}
4

1 回答 1

4

你不需要这样做:

TextToBeDisplayed = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&err];

同样在这种方法中,您不会得到 NSURLRequest,而是 PDF 文件中的某种文本试图转换为 NSURLRequest

NSURLRequest *nsrequest=[NSURLRequest requestWithURL:[NSURL URLWithString:TextToBeDisplayed]];

你只需要这样:

    NSString *filePath;
    filePath = [[NSBundle mainBundle] pathForResource:@"Sample1" ofType:@"pdf"];

    WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:theConfiguration];
    NSURLRequest *nsrequest=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]];


    [webView setBackgroundColor:[UIColor whiteColor]];

    [webView loadRequest:nsrequest];
    [self.view addSubview:webView];
于 2019-03-30T09:29:28.380 回答