2013-02-28 71 views
1

我创建了一个UIWebView并使用HTML文件显示一些内容。但是当我运行它而不是显示内容时,只有整个HTML文件编码才会进入WebView。请帮助并告诉我什么是错的。使用UIWebView显示html文件

UIWebView *ingradients= [[UIWebView alloc]init]; 
    [ingradients setFrame:CGRectMake(10, 170, 300, 300)]; 
    [ingradients loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"htmlfile" ofType:@"html"]isDirectory:NO]]]; 
    ingradients.delegate=self; 
    [self.view addSubview:ingradients]; 

htmlfile.html包含

<html> 
<body> 
<p><strong>Ingredients</strong></p> 
</body> 
</html> 

而不是显示在大胆 “配料”,它显示htmlfile.html

回答

2

全编码,在你的代码你同含有的HTML代码,因为您的请求总是返回文件htmlfile与保留.html

如果你想从HTML内容中获得具体的价值,你需要帕尔斯HTML内容通过使用Hpple。此外,这是用于解析HTML内容的documentation with exmple

你的情况,你使用:(使用Hpple

TFHpple *dataParser = [TFHpple hppleWithHTMLData:placesData]; 

    // name of place 
NSString *XpathQueryString = @"//p/strong"; 
NSArray *listOfdata= [dataParser searchWithXPathQuery: XpathQueryString]; 
+0

刚才我注意到,当我在浏览器中打开HTML文件还显示其在整个编码。你能告诉我会有什么问题吗? – Newbee 2013-02-28 08:47:59

+0

更改URl和检查 – iPatel 2013-02-28 08:50:04

+0

我实际上已经尝试** loadHTMLstring **方法,并将HTML编码作为字符串参数,并且其工作正常.... :) – Newbee 2013-02-28 09:09:54

2

这是奇怪的,我有类似的代码,这和HTML呈现为富文本,但不为纯文本(像你一样),我唯一的区别是使用fileURLWithPath:而不是fileURLWithPath:isDirectory:。这是我的代码:

NSString *localFilePath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"html"]; 
NSURLRequest *localRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:localFilePath]]; 
[_aboutWebView loadRequest:localRequest]; 

也许你有一些文件编码问题,但据我猜测,应该不是这样。

+0

刚才我注意到,当我在浏览器中打开该HTML文件也显示了整个编码。你能告诉我会有什么问题吗? – Newbee 2013-02-28 08:47:12

0

试试这个代码:

- (NSString *) rootPath{ 
    return [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject]; 
} 

- (NSString *) pathFoResourse : (NSString *) resourseName ofType: (NSString *)type{ 
    NSString *path = [[MMSupport rootPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", resourseName, type]]; 
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { 
     path = [[NSBundle mainBundle] pathForResource:resourseName ofType:type]; 
    } 
    NSLog(@"**path:%@**", path); 
    return path; 
} 

- (void) loadDataToWebView : (CGRect) frame{ 
    NSString *htmlString = [NSstring stringWithContentsOfFile:[MMSupport pathFoResourse:@"filename" ofType:@"html"] encoding:NSUTF8StringEncoding) error:nil]; 
    UIWebView *webView = [[UIWebView alloc] initWithFrame:frame]; 
    [webView loadHTMLString:htmlString baseURL:nil]; 
}