我显示UIWebView的本地PDF文件,但它显示的异常路径这里是我的代码
NSString*fileName=content_Source;
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[webView loadRequest:request]
首先验证串并分配到URL像波纹管..
NSString *strURLPath = [self trimString: path];
NSURL *url = [NSURL fileURLWithPath:strURLPath];
用我的方法,波纹管...
-(NSString*) trimString:(NSString *)theString {
if (theString != [NSNull null])
theString = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
return theString;
}
您必须使用文件扩展名,同时设置文件名。 所以一定要确保扩展不会在文件名中使用,如果它与类型一起设置(如ofType:@“PDF”)。
这里是我的代码:
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];
有一个更好的方式来显示PDF文件:
UIDocumentInteractionController *dc = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
dc.delegate = self;
[dc presentPreviewAnimated:YES];
确保使用委托与代码一起正常工作了。
(UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
return self;
}
这是工作的罚款与给定的代码的问题是,在我的文件的名字,我也给像ali.pdf类型,他们PDF类型,因此得到例外,现在工作得很好,当我使用的文件名类似以下
NSString*fileName=@"ali";
代替
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];