iOS WebView的用法

一、UIWebView 可以加载和显示某个URL的网页,也可以显示基于HTML的本地网页或部分网页:
a. 加载 URL

1
2
3
4
WebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)];   
NSString *path = @"http://www.baidu.com";   
NSURL *url = [NSURL URLWithString:path];   
[WebView loadRequest:[NSURLRequest requestWithURL:url]];

b. 加载 HTML

1
2
3
4
5
NSBundle *bundle = [NSBundle mainBundle];
NSString *resPath = [bundle resourcePath];
NSString *filePath = [resPath stringByAppendingPathComponent:@"Home.html"];
[webView loadHTMLString:[NSString stringWithContentsOfFile:filePath]
  baseURL:[NSURL fileURLWithPath:[bundle bundlePath]]];

二、使用网页加载指示,加载完成后再显示网页出来
首先要指定委托方法:
webView.delegate =self;
UIWebView主要有下面几个委托方法:

1
2
3
- (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。
- (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。

这样,可以利用 webViewDidStartLoad 和 webViewDidFinishLoad 方法实现本功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (void) webViewDidStartLoad:(UIWebView *)webView  
{  
    //创建UIActivityIndicatorView背底半透明View        
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];    
    [view setTag:108];    
    [view setBackgroundColor:[UIColor blackColor]];    
    [view setAlpha:0.5];    
    [self.view addSubview:view];    
 
    activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];    
    [activityIndicator setCenter:view.center];    
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];    
    [view addSubview:activityIndicator];    
 
    [activityIndicator startAnimating]; 
}
- (void) webViewDidFinishLoad:(UIWebView *)webView  
{  
    [activityIndicator stopAnimating];  
    UIView *view = (UIView*)[self.view viewWithTag:108];  
    [view removeFromSuperview];  
    NSLog(@"webViewDidFinishLoad");  
}

三、UIWebView还可以通过 stringByEvaluatingJavaScriptFromString 函数来执行 javascript代码,从而可以更加灵活地处理网页文件

1
2
3
4
5
6
7
8
1. 获得UIWebView的标题
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
2. 获取页面的URL
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
3. 修改页面元素的值
NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='朱祁林';"];
4. 表单提交
NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit(); "]

四、综合运用以上方法,还可以实现部分网页的显示,基本思路如下:

1
2
3
4
1. 用 loadRequest 先获取网页,但先设置 UIWebView.hidden = YES;
2. 在 webViewDidFinishLoad 中,用
NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementByIdx_xx_x_x('xxxx').innerHTML; "] 获取指定标签元素的HTML代码
3. 再使用 loadHTMLString 加载该HTML代码,即可

Leave a Reply