长颈鹿但丁

之前做过一个项目,里面涉及到显示公式之类的东西就必须要在项目里面嵌入网页,最麻烦的就是网页需要在本地自己拼凑成html,然后再使用UIWebView加载出来,这里面就涉及到了一些关于OC和JavaScript交互的问题,对于第一次接触这些的人,还是会走一些弯路。我在此把自己学习的分享出来,希望帮到一些人。

分两部分介绍,第一部分是加载本地网页。然后进行交互。第二部分是加载服务器的网页后进行交互。

一 加载本地网页(demo下载地址}

加载本地网页的话,由于网页都是自己写,我们可以把需要的请求参数都提前写好。这样在OC代码里面就可以直接的和网页交互。 OC和js交互的原理是网页发起一个请求,然后WebView截获这个请求,对于这个请求的话可以是很多种的。我的Demo里面也总结了两种不同的方法。

第一种

<script type="text/javascript">function sendCommand(cmd,param){var url="zjq:"+cmd+":"+param;document.location = url;}</script>

第二种

<script language="javascript">function loadURL(url) {var iFrame;iFrame = document.createElement("iframe");iFrame.setAttribute("src", url);iFrame.setAttribute("style", "display:none;");iFrame.setAttribute("height", "0px");iFrame.setAttribute("width", "0px");iFrame.setAttribute("frameborder", "0");document.body.appendChild(iFrame);// 发起请求后这个iFrame就没用了,所以把它从dom上移除掉iFrame.parentNode.removeChild(iFrame);iFrame = null;}function check() {loadURL("zjq:zjqjjqzjq");} </script>

用的比较多也比较简洁的是第一种,第二种的话是发起一个假的请求,一句话,都是为了网页能够刷新一下,WebView的委托才会被调用,才能够拦截到请求,然后做出相应的处理。

1.在界面里面添加一个一个UIWebView和一个按钮,按钮用于OC对网页发起操作currentY = self.navigationController.navigationBar.frame.size.height;screen = [UIScreen mainScreen].bounds.size;_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, currentY, screen.width, screen.height-100)];self.automaticallyAdjustsScrollViewInsets = NO;_webView.delegate = self;// _webView.backgroundColor = [UIColor clearColor];[self.view addSubview:_webView];UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(50, screen.height-50, screen.width-100, 30)];[button addTarget:self action:@selector(appTojs) forControlEvents:UIControlEventTouchUpInside];[button setTitle:@"app向网页发送消息" forState:UIControlStateNormal];[button setBackgroundColor:[UIColor grayColor]];[self.view addSubview:button];2.加载html页面加载页面的方式也很多 NSString * path = [[NSBundle mainBundle] bundlePath];NSURL * baseURL = [NSURL fileURLWithPath:path];NSString * htmlFile = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"html"];NSString * htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:(NSUTF8StringEncoding) error:nil];// 从本地加载一个html文件。[self.webView loadHTMLString:htmlString baseURL:baseURL];这种方式把html当作文件加载 NSString * htmlPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"index.html"];[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]]];这种方法则是相当于发起一个请求3.实现委托函数(js对oc交互)//当网页视图被指示载入内容而得到通知。应当返回YES,这样会进行加载- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{NSURL *url = [request URL];if ([[url scheme] isEqualToString:@"zjq"]) {UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"通知" message:[NSString stringWithFormat:@"%@%@",@"发起请求的url是:",[url absoluteString]]delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];[alertView show];}//多个// 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"])//return YES; }这个返回值一定要是YES的,否则加载不出来,对于上面这个委托方法是用来处理js发起的请求,对于请求的判断,也是可以使用两种不同的方法。上面的源码里面都已经给出。个人更喜欢第一种,如果有多种不同的请求,,又有很对子请求的话第二种应该好一些。//开始请求调用的方法,可以加个指示器- (void)webViewDidStartLoad:(UIWebView *)webView{} //结束请求调用的方法,可以加个指示器- (void)webViewDidFinishLoad:(UIWebView *)webView{}//加载失败的方法- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{NSLog(@"error是%@",error);}4.oc对js交互oc对html进行修改的话,我们使用一个方法就可以。stringByEvaluatingJavaScriptFromString,苹果也就只给了这一个方法。- (void)appTojs{NSString * js = @" var p = document.createElement('p'); p.innerText = '增加一行';document.body.appendChild(p);";[self.webView stringByEvaluatingJavaScriptFromString:js];}饶人不是痴汉,痴汉不会饶人。

长颈鹿但丁

相关文章:

你感兴趣的文章:

标签云: