Display local pdf file in UIWebView in iphone

一笑奈何 提交于 2019-12-04 22:00:15

first validate that string and the assign to URL like bellow..

   NSString *strURLPath = [self trimString: path];
   NSURL *url = [NSURL fileURLWithPath:strURLPath];

use my bellow method...

-(NSString*) trimString:(NSString *)theString {
    if (theString != [NSNull null])
        theString = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return theString;
}
Harjot Singh

You must be using the file name extension while setting the file name. So make sure the extension will not be used in file name if its setting along with Type (like ofType:@"pdf").

Here's my code:

UIWebView *webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
webView.backgroundColor = [UIColor redColor];
NSString*fileName= @"About_Downloads";
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
[webView setScalesPageToFit:YES];
[webView loadRequest:request];
[self.view addSubview:webView];

There's a better way to show pdf's:

UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
dc.delegate = self; 
[dc presentPreviewAnimated:YES];

Make sure use the delegate along with that code to work it properly.

(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

It is working fine with the given code problem was that in my file Name i was giving also the type like ali.pdf they type pdf so it get exception it worked fine now when i use filename like following

 NSString*fileName=@"ali";

Instead of

    NSString*fileName=@"ali.pdf";
CGRect rect = [[UIScreen mainScreen] bounds];
    CGSize screenSize = rect.size;
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"];
    NSURL *targetURL = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [webView loadRequest:request];

    [self.view addSubview:webView];
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!