【问题标题】:Opening PDF files in WKWebView objective c在 WKWebView 目标 c 中打开 PDF 文件
【发布时间】:2019-03-30 09:02:05
【问题描述】:

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

Error Domain=NSCocoaErrorDomain Code=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).
}

【问题讨论】:

    标签: ios objective-c pdf wkwebview wkwebviewconfiguration


    【解决方案1】:

    你不需要这样做:

    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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 2023-03-24
      相关资源
      最近更新 更多