Search code examples
javascriptiosobjective-cuiwebviewjavascriptcore

Is it possible to call an Objective-C function that returns a value to javascript?


I'd like to use JavaScriptCore / JSContext in an iOS Objective-C webview app to return a value to a javascript function.

For example, in javascript: var retVal = myObjC.returnSomething();

where returnSomething is the Objective-C function. For sake of discussion let's say it returns a string to the javascript function.

I've been able to call Objective-C functions that don't return a value, but haven't been able to find anything that describes how to return a value.

Is this even possible with JavaScriptCore, or am I taking the wrong approach to this? I need the javascript to wait for the return value (synchronous).


Solution

  • As you are expecting, passing data from obj C to JS use stringByEvaluatingJavaScriptFromString / passing data from JS to Obj C use JSContext

    <!-- save as .html and load into UIWebview -->
    
        <!DOCTYPE html>
        <html>
        <head>
        <script>
        function loadData(x){
        alert(x);
        }    
        function myMeg(){   
        passDatatoObjC("success");    
        }
        </script>
        </head>
        </html>
    
        function returnSomething(x){
        loadData(x);
        }
    
        function passDatatoObjC(x){
        passDatatoObjC(x);    
        }
    
        #pragma mark - UIWebview dataource
    
        -(void)webViewDidFinishLoad:(UIWebView *)webView{
    
          [self.svgWebMapView   stringByEvaluatingJavaScriptFromString:@"returnSomething(10)"];
    
          JSContext *context =  [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        context[@"passDatatoObjC"] = ^(NSString *msg) {
        NSLog(@"%@",msg);
    
        });
        }