iOS, JavaScript 와 통신

Posted on 2018-10-18(목) in iOS

1. JavaScript의 console.log 를 NSLog 로 찍어 보기.

  • ViewController.m : 44라인
JSContext *ctx = [_webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

ctx[@"console"][@"log"] = ^(JSValue * msg) {
    NSLog(@"%@ log message: %@", [JSContext currentContext], msg);
};
  • test.html : 19, 31라인
console.log('=== Java Script Start ===>');
console.log('<=== Java Script End ===');

2. JavaScript 에서 비동기(async)로 NSLog 로 찍어 보기.

  • ViewController.m : 44라인
ctx[@"callbackToiOSFromJavaScript"] = ^(JSValue * msg) {
    NSLog(@"%@ : %@", [JSContext currentContext], msg);
};
  • test.html : 16, 28라인
<div id="btnIOS">iOS로 callbackToiOSFromJavaScript 호출하기</div>
<script>
$('#btnIOS').click(function(){
    callbackToiOSFromJavaScript('"JavaScript" ==> "iOS" 로 이 메세지를 보냄!!!');
});
</script>

3. iOS 에서 JavaScript Function 을 호출해 보기.

  • ViewController.m : 44라인
- (IBAction)clickedSendButton:(id)sender {
  NSString *jscbString = [NSString stringWithFormat:@"commandFromiOSToJavaScript('first', 'second')"];
  NSLog(@"------> jscbString : [%@]", jscbString);
  NSString *result = [_webView stringByEvaluatingJavaScriptFromString:jscbString];
  NSLog(@"------> result : [%@]", result);
}
  • test.html : 16, 28라인
<div id="divIOS"></div>
<script>
    var divIOS = $('#divIOS');

    function commandFromiOSToJavaScript(firstArg, secondArg)
    {
        divIOS.html(divIOS.html() + 'First Arg : ' + firstArg + ', Second Arg : ' + secondArg + '<br />');
        return 'ok!'
    }
</script>
2017-07-09 01:26:25.610 WebViewTest001[82455:666602]  log message: === Java Script Start ===>
2017-07-09 01:26:25.612 WebViewTest001[82455:666602]  log message: <=== Java Script End === 2017-07-09 01:27:06.315 WebViewTest001[82455:666562] ------> jscbString : [commandFromiOSToJavaScript('first', 'second')]
2017-07-09 01:27:06.317 WebViewTest001[82455:666562] ------> result : [ok!]
2017-07-09 01:27:07.508 WebViewTest001[82455:666562] ------> jscbString : [commandFromiOSToJavaScript('first', 'second')]
2017-07-09 01:27:07.509 WebViewTest001[82455:666562] ------> result : [ok!]
2017-07-09 01:27:08.869 WebViewTest001[82455:666562] ------> jscbString : [commandFromiOSToJavaScript('first', 'second')]
2017-07-09 01:27:08.871 WebViewTest001[82455:666562] ------> result : [ok!]
2017-07-09 01:27:11.008 WebViewTest001[82455:666562] ------> jscbString : [commandFromiOSToJavaScript('first', 'second')]
2017-07-09 01:27:11.009 WebViewTest001[82455:666562] ------> result : [ok!]
2017-07-09 01:27:30.969 WebViewTest001[82455:666602] : "JavaScript" ==> "iOS"   메세지를 보냄!!!
2017-07-09 01:27:32.329 WebViewTest001[82455:666602] : "JavaScript" ==> "iOS"   메세지를 보냄!!!
2017-07-09 01:27:33.532 WebViewTest001[82455:666602] : "JavaScript" ==> "iOS"   메세지를 보냄!!!
2017-07-09 01:27:34.855 WebViewTest001[82455:666602] : "JavaScript" ==> "iOS"   메세지를 보냄!!!

iOS JavaScript