uniapp混合开发js调⽤oc代码和oc调⽤js
js调⽤oc类⽅法
//LoginViewController是oc类 txt是要传的参数
plus.ios.importClass("LoginViewController").login("txt“);
js调⽤oc对象⽅法
//objectToJsonImage是oc对象⽅法 massageArray返回值
var Massage = plus.ios.importClass("LoginViewController");
var massage =new Massage();
var massageArray = massage.objectToJsonImage();
oc 调⽤js
(NSMutableArray*)searchViews:(NSArray*)views{
NSMutableArray *frames =[NSMutableArray array];
//遍历view
for(UIView *temp in views){
if([temp isMemberOfClass:[PDRCoreAppFrame class]]){
[frames addObject:temp];
}
if([temp subviews]){
NSMutableArray *tempArray =[self searchViews:[temp subviews]];
for(UIView *tempView in tempArray){
if([tempView isMemberOfClass:[PDRCoreAppFrame class]]){
[frames addObject:tempView];
}
}
}
}
//返回值 frames 为从该层级中到的 PDRCoreAppFrame
return frames;
}
(void)evaluatingJavaScriptFromString:(NSString*)string{
UIWindow *window =[[UIApplication sharedApplication] keyWindow];
NSArray *views =[[[window rootViewController] view] subviews];
NSArray *frames =[self searchViews:views];
for(PDRCoreAppFrame *appFrame in frames){
/*这⾥需要注意执⾏异步任务,在block内需要回到主线程来进⾏JS event的调⽤,但是如果还是使⽤
dispath_get_main_queue的话会造成调⽤JS有alert的话线程会死锁,具体原因也不是特别清晰,
在stackOverFlow中看到应该是JS和OC不同alert线程的原因
*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{
[appFrame performSelectorOnMainThread:@selector(stringByEvaluatingJavaScriptFromString:) withObject:string waitUntilDone:NO];
});
}
}
(void)fireEvent:(NSString*)event args:(NSString *)args{
NSString *evalStr = nil;
if(args){
if(args){
//创建js事件
evalStr =[NSString stringWithFormat:@"\
var pathEvent = ateEvent('HTMLEvents');\ pathEvent.initEvent('%@', true, true);\
pathEvent.eventType ='message';\
pathEvent.arguments ='%@';\
document.dispatchEvent(pathEvent);",event,args];
}else{
js argumentsevalStr =[NSString stringWithFormat:@"\
var pathEvent = ateEvent('HTMLEvents');\ pathEvent.initEvent('%@', true, true);\
pathEvent.eventType ='message';\
document.dispatchEvent(pathEvent);",event];
}
//return evalStr;
//调⽤上述⽅法
[self evaluatingJavaScriptFromString:evalStr];
}
//通过此代码调⽤
[self fireEvent:@"event_name" args:@"json"];
//js端代码
document.addEventListener('event_name',function(e){
alert(e.arguments);
}, false);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论