oc调用js的方法

在JavaScript中调用Objective-C(OC)的方法,可以通过以下几种方式实现:

通过获取JSContext的方式直接调用OC方法

你可以通过UIWebViewjavaScriptContext属性获取JavaScript的上下文,然后在这个上下文中调用OC方法。例如:

objective-c<p> - (void)webViewDidFinishLoad:(UIWebView *)webView {<p> // 获取JavaScript上下文<p> JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];</p><p> // 设置一个JavaScript方法<p> [jsContext setObject:self forKeyedSubscript:@"getMessage" options:0 context:nil];<p> }</p><p> - (NSString *)blockCallMessage {<p> return @"call via block";<p> }<p>

然后在JavaScript中,你可以这样调用这个方法:

javascript<p> getMessage();<p>

通过继承自JSExport的方式调用delegate中的方法

你可以创建一个类,继承自JSExport,并在这个类中实现一些方法,然后在JavaScript中调用这些方法。例如:

objective-c<p> @interface MyJavaScriptExport : NSObject <JSExport><p> - (NSString *)tipMessage;<p> @end</p><p> @implementation MyJavaScriptExport<p> - (NSString *)tipMessage {<p> return @"call via delegate";<p> }<p> @end<p>

然后在JavaScript中,你可以这样调用这个方法:

javascript<p> MyJavaScriptExport.tipMessage();<p>

通过截取URL的方式

你可以通过拦截UIWebViewshouldStartLoadWithRequest:navigationType:代理方法,解析URL中的参数,然后调用相应的OC方法。例如:

objective-c<p> - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {<p> NSURL *url = [request URL];<p> NSString *urlStr = request.URL.absoluteString;<p> NSString *scheme = @"test://";</p><p> if ([urlStr hasPrefix:scheme]) {<p> // 解析URL中的参数<p> NSString *temp = [urlStr substringFromIndex:scheme.length];<p> NSArray *subPaths = [temp componentsSeparatedByString:@"?"];<p> // 调用相应的OC方法<p> [self performSelector:@selector(someMethod:) withObject:[subPaths objectAtIndex:0]];<p> }</p><p> return YES;<p> }<p>

然后在JavaScript中,你可以这样调用这个方法:

javascript<p> window.location = "test://someParameter";<p>

这些方法都可以实现JavaScript调用Objective-C的方法,具体使用哪种方式取决于你的需求和项目结构。