最近公司项目组长添加了一种JS与OC交互的方法,一直想研究,于是乎就各种百度,下面把我觉得让我思路打开的几篇文章分享给大家,后续有时间会补上相关使用Demo。
iOS js oc相互调用(JavaScriptCore)
iOS js oc相互调用(JavaScriptCore)(二)
关于JS和OC交互
iOS与JS交互实战篇(ObjC版)
JS&iOS原生交互
webView与js交互、
再给大家看一下项目中实际的代码吧
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "ParentWebView.h"
/** 用于传值的Block,具体传值克根据需要自定义 **/
typedef void(^ CLMarketModelBlock)(NSString *type,NSString *mainType,NSString *urlStr);
@protocol JavaScriptObjectiveCDelegate <JSExport>
/** 以下的方法名称是需要跟JS涉及的方法名相对应的一致的命名 **/
- (void) goodsCar;
- (void) reserveFlower;
- (void) huacaoReserve;
- (void)list:(NSString *)categorId Detail:(NSString *)Property ;
- (void) go: (NSString *)url Looper: (NSString *)title;
- (void) reserveListDetail:(NSString *)Date;
@end
@interface CLMarketModel : NSObject<JavaScriptObjectiveCDelegate>
@property (nonatomic, weak) JSContext *jsContext1;
@property (nonatomic, weak) ParentWebView *webView1;
@property (nonatomic ,strong) NSString *type;
@property (nonatomic ,copy) CLMarketModelBlock CLMarketBlock;
@end
#import "CLMarketModel.h"
#import "MaketViewController.h"
@implementation CLMarketModel
- (void)goodsCar {
self.CLMarketBlock(_type,nil,nil);
}
- (void)reserveFlower {
NSString *str = [NSString stringWithFormat:@"%@%@",E_InsideUrl,@"/easyflower/h5_3/yh_huacaiyuding.html?app=ios"];
self.CLMarketBlock(str,EF_YUDING,nil);
}
- (void) huacaoReserve {
self.CLMarketBlock(nil,EF_HUACAOYUDING,nil);
}
- (void) list:(NSString *)categorId Detail:(NSString *)Property {
self.CLMarketBlock (nil,EF_SHANGPIN,nil);
}
- (void) go: (NSString *)url Looper: (NSString *)title {
self.CLMarketBlock(nil,EF_QITAURL,url);
}
- (void)reserveListDetail:(NSString *)Date {
self.CLMarketBlock (nil,nil,Date);
}
@end
#import "CLMarketModel.h"
#import <JavaScriptCore/JavaScriptCore.h>
{
JSContext *_mainJsContxt;
}
/****************************************************************************************************************************************************************************************************************************/
_mainJsContxt = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
CLMarketModel *model = [[CLMarketModel alloc] init];
_mainJsContxt[@"JSInterface"] = model;
model.jsContext1 = _mainJsContxt;
model.webView1 = _Myweb;
__weak __typeof(self)weakSelf = self;
model.CLMarketBlock = ^(NSString *type ,NSString *mainTYpe,NSString *Urlstr)
{
/** 根据传值不同做不同的操作即可 **/
};
_mainJsContxt.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
/** 程序异常时的相关操作放到这里即可 **/
};
网友评论