1

I'm having troubles visualizing the content of pdf files using WKWebView and objective c. Sorry, I'm not familiar with Swift. Here is the code, but it shows a blank page and it returns the following error:

Error Domain=NSCocoaErrorDomain Code=261 "The file “Sample1.pdf” couldn’t be opened using text encoding Unicode (UTF-8).

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).
}
jeddi
  • 651
  • 1
  • 12
  • 21

1 Answers1

6

You don't need to do this:

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

Also in this method you'll get not NSURLRequest, but some kind of text from inside your PDF file trying to transform to NSURLRequest

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

All you need is this:

    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];
Anton Novoselov
  • 769
  • 2
  • 7
  • 19