![](/img/trans.png)
[英]Display Local HTML file from documents directory in a UIWebView on iPhone
[英]Display local pdf file in UIWebView in iphone
我在 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]
設置文件名時必須使用文件擴展名。 因此,如果擴展名與類型一起設置(如 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;
}
首先驗證該字符串並分配給 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;
}
對於給定的代碼問題,它工作正常,因為在我的文件名中,我還提供了類似 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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.