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) {
    
      
    //创建js事件  
    evalStr = [NSString stringWithFormat:@"\  
               var pathEvent = document.createEvent('HTMLEvents');\  
               pathEvent.initEvent('%@', true, true);\  
               pathEvent.eventType = 'message';\  
               pathEvent.arguments = '%@';\  
               document.dispatchEvent(pathEvent);",event,args];  
}else{
    
      
    evalStr = [NSString stringWithFormat:@"\  
               var pathEvent = document.createEvent('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);

おすすめ

転載: blog.csdn.net/qq_25430563/article/details/120140040
おすすめ