iOS的UIWebView用法
UIWebView的使用方法
//1.创建、设置代理 UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 300)]; webView.delegate = self; //2.加载网页 NSURL *url=[NSURL URLWithString:@"http://www.google.com.hk"]; NSURLRequest *request=[[NSURLRequest alloc] initWithURL:url]; [webView loadRequest:request]; //3.加载本地资源 NSURL* url = [NSURL fileURLWithPath:filePath]; NSURLRequest* request = [NSURLRequest requestWithURL:url]; [webView loadRequest:request]; //4.是否与用户交互(即用户能不能控制webview) [webView setUserInteractionEnabled:YES]; //5.显示 UIWebView [self.view addSubview:webView]; //6.导航 [webView goBack];//返回 [webView goForward];//向前 [webView reload];//重新加载数据 [webView stopLoading];//停止加载数据 //7.自动对页面进行缩放以适应屏幕 webView.scalesPageToFit = YES; //8.自动检测网页上的电话号码,单击可以拨打 webView.detectsPhoneNumbers = YES; //9.UIWebView 还支持将一个NSString对象作为源来加载。你可以为其提供一个基础URL,来指导UIWebView对象如何跟随链接和加载远程资源 [webView loadHTMLString:myHTML baseURL:[NSURL URLWithString:@"http://baidu.com"]]; //10.UIWebView和JS交互 //(1)在Objective-C代码中调用JS //使用stringByEvaluatingJavaScriptFromString方法,需要等到UIWebView中的页面加载完成之后去调用。 -(void) webViewDidFinishLoad:(UIWebView *)webView{ [self.activityViewstopAnimating]; [myWebView stringByEvaluatingJavaScriptFromString:@"function test(){ alert(123123123)}"]; [myWebView stringByEvaluatingJavaScriptFromString:@"test();"];//调用 } //(2)在JS中调用Objective-C代码 //JS代码: function sendCommand(cmd,param){ var url="testapp:"+cmd+":"+param; document.location = url; } function clickLink(){ sendCommand("alert","你好吗?"); } //Objective-C代码: - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *requestString = [[request URL] absoluteString]; NSArray *components = [requestString componentsSeparatedByString:@":"]; if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) { if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2] delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil nil]; [alert show]; } return NO; } return YES; }
UIWebView的委托方法
//1.web视图指示加载内容时通知。应该返回YES开始加载。导航提供的类型参数,是指请求的来源,可以是下列任何一个: //UIWebViewNavigationTypeLinkClicked 用户触击了一个链接 //UIWebViewNavigationTypeFormSubmitted 用户提交了一个表单 //UIWebViewNavigationTypeBackForward 用户触击前进或返回按钮 //UIWebViewNavigationTypeReload 用户触击重新加载的按钮 //UIWebViewNavigationTypeFormResubmitted 用户重复提交表单 //UIWebViewNavigationTypeOther 发生其它行为 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; //2.开始加载的时候执行该方法。 - (void)webViewDidStartLoad:(UIWebView *)webView; //3.加载完成的时候执行该方法。 - (void)webViewDidFinishLoad:(UIWebView *)webView; //4.加载出错的时候执行该方法。 - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;