如何在IOS平台上使用js直接调用OC方法

JavaScript016

如何在IOS平台上使用js直接调用OC方法,第1张

本例子是为了让大家能快速开发出OC调用JS功能的一个简单的例子。

1、准备一个本地化的html网页,如jsIOS.html

<script type="text/javaScript">

function postStr(){

return document.getElementById("text1").value

//return "javaScript返回值啦"

}

</script>

2、将此html文件放到项目代码目录里面,如图:

3、拖一个UIWebView控件和UIButton控件到xxxViewController对应的.xib或.storyboard视图的UIView上;

在xxxViewController的.h文件中分别声明UIWebView类型变量和UIButton类型的变量,以及一个按钮点击事件(并且跟视图里面的控件连线),

并且添加一个UIWebViewDelegate类型的委托。<喎�"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+eHh4Vmlld0NvbnRyb2xsZXIuaM7EvP7E2sjdyOfPwqO6PC9wPgo8cD48L3A+CjxwIGNsYXNzPQ=="p1">

#import

@interface ViewController : UIViewController

@property(nonatomic,retain) IBOutlet UIWebView *webview

@property(nonatomic,retain) IBOutlet UIButton *button

-(IBAction)IOS_JS:(id)sender

@end

4、在xxxViewController.m文件中实现通过点击事件,调用javaScript的方法并取得返回值。

代码如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize webview

- (void)viewDidLoad

{

[super viewDidLoad]

//设置webView

webview.backgroundColor = [UIColor clearColor]

//webview.scalesPageToFit =YES

webview.delegate =self

//找到jsIOS.html文件的路径

NSString *basePath = [[NSBundle mainBundle]bundlePath]

NSString *helpHtmlPath = [basePath stringByAppendingPathComponent:@"jsIOS.html"]

NSURL *url = [NSURL fileURLWithPath:helpHtmlPath]

//加载本地html文件

[webview loadRequest:[NSURLRequest requestWithURL:url]]

}

/*

* 点击事件

* 调用javaScript的方法postStr()并取得返回值

* 输出返回值到控制台

*/

-(IBAction)IOS_JS:(id)sender

{

NSString *str = [self.webview stringByEvaluatingJavaScriptFromString:@"postStr()"]

NSLog(@"JS返回值:%@",str)

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning]

}

@end

使用示例: 下面的示例代码将调用上面NativeOcClass的方法,在js层只需要这样调用: var ret = jsb.reflection.callStaticMethod("NativeOcClass", "callNativeUIWithTitle:andContent:", "cocos2d-js", "Yes! you call a Native UI from Reflect.

基本流程:

先看一下Web中,我们给h1标签添加一个onclick事件,让它在被点击之后,修改当前的url。

Web中的HTML代码:

<html>

<head>

<script>

function getInfo(name)

{

window.location = "/getInfo/"+name

}

</script>

</head>

<body>

<h1 onclick="getInfo('why')">Name</h1>

</body>

</html>

iOS中,先拖拽WebView,访问localhost,然后通过WebView的委托事件监听url跳转操作,并且把跳转截取下来。

也就是说,在onclick的时候,普通浏览器灰跳转到那个url,但是在iOS的这个WebView里面,这个跳转会被拦截,

用这种方式可以巧妙地实现JS调用iOS的原生代码:

//

// DWViewController.m

// DareWayApp

//

// Created by why on 14-6-3.

// Copyright (c) 2014年 DareWay. All rights reserved.

//

#import "DWViewController.h"

@interface DWViewController ()

@property (weak, nonatomic) IBOutlet UIWebView *myWebview // 主页面

@end

@implementation DWViewController

- (void)viewDidLoad

{

[super viewDidLoad]

// Do any additional setup after loading the view, typically from a nib.

// 适配iOS6的状态栏

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {

_myWebview.frame = CGRectMake(0,20,self.view.frame.size.width,self.view.frame.size.height-20)

}

// 加载制定的URL

NSURL *url =[NSURL URLWithString:@"http://localhost"]

NSURLRequest *request =[NSURLRequest requestWithURL:url]

[_myWebview setDelegate:self]

[_myWebview loadRequest:request]

}

// 网页中的每一个请求都会被触发

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

{

// 每次跳转时候判断URL

if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/why"])

{

NSLog(@"why")

return NO

}

return YES

}

- (void)didReceiveMemoryWarning

{

[super didReceiveMemoryWarning]

// Dispose of any resources that can be recreated.

}

@end