美文网首页
JS和app交互

JS和app交互

作者: 过眼云烟1102 | 来源:发表于2017-06-16 21:41 被阅读102次

一、    H5上代码的对接要点:1.Object类型的传参、2.同一个与app交互的JS方法、3.脚本方法需内嵌到head里面。

Objective-C和JavaScript交互的那些事

点击调用原生代码并传递参数  二、    IOS上的代码对接  注意点:#import需放在.h文件中 #import"ViewController.h"#import@interfaceViewController ()@property (nonatomic)UIWebView*webView;

@property(nonatomic)JSContext *jsContext;

@property(nonnull,strong) UIButton *btn;

@end

@implementationViewController

-(void)viewDidLoad{

[super viewDidLoad];

self.webView = [[UIWebViewalloc]initWithFrame:self.view.bounds];

self.webView.delegate = self;

[self.view addSubview:_webView];

NSString *str = [[NSBundle mainBundle]pathForResource:@"migi" ofType:@"html"];

[self.webView loadRequest:[NSURLRequestrequestWithURL:[NSURL fileURLWithPath:@"f"]]];

//  在上面添加一个按钮,实现oc端控制h5实现弹alert方法框

self.btn = [[UIButton alloc]initWithFrame:CGRectMake(100,400, 100, 40)];

self.btn.backgroundColor = [UIColorredColor];

[self.btn addTarget:selfaction:@selector(showAlert) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:self.btn];

}

-(void)showAlert

{

//要将script的alert()方法转化为string类型

NSString *alertJs=@"alert('Hello Word')";

[_jsContext evaluateScript:alertJs];

}

-(void)webViewDidFinishLoad:(UIWebView*)webView{

_jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

_jsContext[@"startFunction"] =^(id obj){

////这里通过block回调从而获得h5传来的json数据

/*block中捕获JSContexts

我们知道block会默认强引用它所捕获的对象,如下代码所示,如果block中直接使用context也会造成循环引用,这使用我们最好采用[JSContext currentContext]来获取当前的JSContext:

*/

[JSContext currentContext];

NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ];

NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:nil];

NSLog(@"data  %@  ====== ShareUrl %@",obj,dict[@"shareUrl"]);

};

//

_jsContext.exceptionHandler = ^(JSContext*context, JSValue *exceptionValue) {

context.exception = exceptionValue;

//比如把js中的方法名改掉,OC找不到相应方法,这里就会打印异常信息

NSLog(@"异常信息:%@", exceptionValue);

};

_jsContext[@"testFunction"] =^(id obj){

//这里通过block回调从而获得h5传来的json数据

[JSContext currentContext];

NSData *data = [(NSString *)obj dataUsingEncoding:NSUTF8StringEncoding ];

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

//            NSLog(@" data  %@  ======  ShareUrl%@",obj,dict[@"shareUrl"]);

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:dict[@"title"] message:dict[@"content"] delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];

[alertView show];

};

}

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

{

NSURL * url = [requestURL];

//NSLog(@"scheme信息:%@", [urlscheme]);

if ([[url scheme] isEqualToString:@"testfunction"])

{

NSArray *params =[url.query componentsSeparatedByString:@"&"];

NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];

for (NSString *paramStr in params) {

NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];

if (dicArray.count > 1) {

NSString *decodeValue =[dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[tempDic setObject:decodeValue forKey:dicArray[0]];

}

}

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:tempDic[@"title"] message:tempDic[@"content"] delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];

[alertView show];

NSLog(@"tempDic:%@",tempDic);

return NO;

}

return true;  //为yes加载内容,否则不

}

相关文章

网友评论

      本文标题:JS和app交互

      本文链接:https://www.haomeiwen.com/subject/ehhtgttx.html