IOS 与 JS 交互
2016-06-17 16:26
302 查看
导入 JavaScriptCore.framework
准备一个HTML文件:
协议必须继承与 JSExport
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol customJavaScriptDelegate <JSExport>
- (void)call:(NSString * )string;
@end
#import "ViewController.h"
#import "customJavaScriptDelegate.h"
@interface
ViewController ()<UIWebViewDelegate,customJavaScriptDelegate>
@property (nonatomic,strong)UIWebView * Web;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColororangeColor];
//获取本地HTML
NSString * htmlPath = [[NSBundlemainBundle]pathForResource:@"test"ofType:@"html"];
NSURL *url=[NSURLfileURLWithPath:htmlPath];
//创建一个UIWebView
self.Web = [[UIWebViewalloc]initWithFrame:CGRectMake(0,150,
400,
300)];
[self.WebloadRequest:[NSURLRequestrequestWithURL:url]];
self.Web.delegate =self;
[self.viewaddSubview:self.Web];
UIButton * button = [[UIButtonalloc ]initWithFrame:CGRectMake(50,550,70,45)];
[button addTarget:selfaction:@selector(buttonTest:)forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"OC调JS·"forState:UIControlStateNormal];
button.backgroundColor = [UIColorredColor];
[self.viewaddSubview:button];
}
- (void)buttonTest:(UIButton *)sender{
//调用JS方法并返回值
NSString * backStr= [self.WebstringByEvaluatingJavaScriptFromString:[NSStringstringWithFormat:@"test4('%@','%@')",@"ABCD",@"EFG"]];
NSLog(@"=============== %@",backStr);
}
//刚要开始加载时调用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url=request.URL;
//判断scheme是否是自定义的
if([url.schemeisEqualToString:@"native"])
{
//判断host是什么方法
if([url.hostisEqualToString:@"log"])
{
//将query param拼接起来
NSString *query=url.query;
//分割字符
NSArray *arr=[query
componentsSeparatedByString:@"&"];
NSMutableDictionary *dic=[NSMutableDictionarydictionary];
for(NSString *strin arr)
{
NSArray *arrItem=[str
componentsSeparatedByString:@"="];
dic[arrItem[0]]=arrItem[1];
}
NSLog(@"输出%@",dic[@"pwd"]);
}
return NO;
}
return
YES;
}
//加载完成后调用
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//获取JSContext对象,对应javascript上下文里的window对象
JSContext *context=[webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//将本类对象注入JS中 让JS调用call方法
context[@"callOC"] =
self;
context[@"log"]=^(NSString * str)
{
NSLog(@"===== %@",str);
};
}
//加载失败后条用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"error:%@",error);
}
/**
* 协议方法
*/
- (void)call:(NSString *)param
{
NSLog(@"JS返回的参数param:%@",param);
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
效果图
控制台:
准备一个HTML文件:
协议必须继承与 JSExport
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@protocol customJavaScriptDelegate <JSExport>
- (void)call:(NSString * )string;
@end
#import "ViewController.h"
#import "customJavaScriptDelegate.h"
@interface
ViewController ()<UIWebViewDelegate,customJavaScriptDelegate>
@property (nonatomic,strong)UIWebView * Web;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColororangeColor];
//获取本地HTML
NSString * htmlPath = [[NSBundlemainBundle]pathForResource:@"test"ofType:@"html"];
NSURL *url=[NSURLfileURLWithPath:htmlPath];
//创建一个UIWebView
self.Web = [[UIWebViewalloc]initWithFrame:CGRectMake(0,150,
400,
300)];
[self.WebloadRequest:[NSURLRequestrequestWithURL:url]];
self.Web.delegate =self;
[self.viewaddSubview:self.Web];
UIButton * button = [[UIButtonalloc ]initWithFrame:CGRectMake(50,550,70,45)];
[button addTarget:selfaction:@selector(buttonTest:)forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"OC调JS·"forState:UIControlStateNormal];
button.backgroundColor = [UIColorredColor];
[self.viewaddSubview:button];
}
- (void)buttonTest:(UIButton *)sender{
//调用JS方法并返回值
NSString * backStr= [self.WebstringByEvaluatingJavaScriptFromString:[NSStringstringWithFormat:@"test4('%@','%@')",@"ABCD",@"EFG"]];
NSLog(@"=============== %@",backStr);
}
//刚要开始加载时调用
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *url=request.URL;
//判断scheme是否是自定义的
if([url.schemeisEqualToString:@"native"])
{
//判断host是什么方法
if([url.hostisEqualToString:@"log"])
{
//将query param拼接起来
NSString *query=url.query;
//分割字符
NSArray *arr=[query
componentsSeparatedByString:@"&"];
NSMutableDictionary *dic=[NSMutableDictionarydictionary];
for(NSString *strin arr)
{
NSArray *arrItem=[str
componentsSeparatedByString:@"="];
dic[arrItem[0]]=arrItem[1];
}
NSLog(@"输出%@",dic[@"pwd"]);
}
return NO;
}
return
YES;
}
//加载完成后调用
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//获取JSContext对象,对应javascript上下文里的window对象
JSContext *context=[webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//将本类对象注入JS中 让JS调用call方法
context[@"callOC"] =
self;
context[@"log"]=^(NSString * str)
{
NSLog(@"===== %@",str);
};
}
//加载失败后条用
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
NSLog(@"error:%@",error);
}
/**
* 协议方法
*/
- (void)call:(NSString *)param
{
NSLog(@"JS返回的参数param:%@",param);
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
效果图
控制台:
相关文章推荐
- 您所不知道的nil/Nil/NULL/NSNull的空与空
- 2016年GitHub 排名前 100 的安卓、iOS项目简介(收藏)
- 二叉树相关算法实现-iOS
- iOS webView获取html内容
- ios学习路线—iOS高级(Masonry)
- IOS上MDM技术资料
- iOS 开发资料库
- iOS大神牛人的博客集合
- iOS键盘优化细节
- ios aop 和 swizzmethod
- ios学习路线—iOS高级(VFL语言)
- 一篇介绍ios证书的博客
- 在iOS平台上使用js直接调用OC方法
- iOS之获取经纬度并通过反向地理编码获取详细地址
- IOS培训实战教程之开发的21个奇葩技巧
- 自定义View:仿ios开关按钮控件
- iOS设置键盘上Return按键及点击操作
- iOS Frame与bounds的区别与联系
- ERROR 0199: Security password retry count exceeded.
- Runtime 获取成员变量列表