>  기사  >  웹 프론트엔드  >  OC와 JS 상호작용을 구현하기 위해 JavaScriptCore를 사용한 샘플 코드에 대한 자세한 설명

OC와 JS 상호작용을 구현하기 위해 JavaScriptCore를 사용한 샘플 코드에 대한 자세한 설명

黄舟
黄舟원래의
2017-03-28 14:09:291039검색

JavaScriptCore는 웹킷의 중요한 부분으로 주로 JS를 구문 분석하고 실행을 제공합니다. 다음 글에서는 JavaScriptCore를 사용하여 OC와 JS 간의 상호작용을 구현하는 방법에 대한 정보를 주로 소개합니다. 필요한 친구들은 함께 살펴보세요. >

JavascriptCore

JavascriptCore는 주로 JS를 파싱하고 실행 환경을 제공하는 부분입니다. 이는 큰 성공을 거두었습니다.

먼저 webView를 만들고 로컬 HTML 파일을 읽습니다.

 NSURL* htmlURL = [[NSBundle mainBundle] URLForResource: @"demo" withExtension: @"html"];
[_webView loadRequest: [NSURLRequest requestWithURL: htmlURL]];

데모에서는 4가지 상황 구현

  1. JS가 OC 호출

  2. JS가 OC를 호출하고 매개변수 전달

  3. OC Call JS

  4. OC는 JS를 호출하고 매개변수를 전달합니다


html 파일의 코드는 다음과 같습니다

<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <script type="text/javascript">
 function showAlert(){
  alert(&#39;OC call JS with no argument&#39;);
 }
 function showAlertWithString(string){
  alert(string);
 }
 function callOCWithArgument() {
  jsCallOCWithArgument(&#39;参数1 &#39;,&#39;参数2 &#39;,&#39;参数3&#39;);
 }
 </script>
</head>
<body>
 </br>
 </br>
 </br>
 </br>
 <form>
  <button type=&#39;button&#39; onclick=&#39;callOC()&#39;>jsCallOC</button>
  <button type=&#39;button&#39; onclick=&#39;callOCWithArgument()&#39;>jsCallOCWithArgument</button>
 </form>
</body>
</html>

JS는 OC를 호출합니다

webView의 프록시 메소드 webViewDidFinishLoad

-(void)webViewDidFinishLoad:(UIWebView *)webView
{

 _context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javascriptContext"];
 weak typeof(self) weakSelf = self;
 _context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
  weakSelf.context.exception = exception;
 };

 //js调用OC
 _context[@"callOC"] = ^() {
  NSArray *args = [JSContext currentArguments];
  for (JSValue *jsVal in args) {
   NSLog(@"%@", jsVal.toString);
  }
  dispatch_async(dispatch_get_main_queue(), ^{
   UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" 
   message:@"JS Call OC With No Argument" preferredStyle:UIAlertControllerStyleAlert];
   UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

   }];
   [alertView addAction:action];
   [weakSelf presentViewController:alertView animated:YES completion:nil];
  });
 };

 _context[@"jsCallOCWithArgument"] = ^() {
  NSArray *args = [JSContext currentArguments];
  NSMutableString * stirng = [NSMutableString string];
  for (JSValue * value in args) {
   [stirng appendString:value.toString];
  }
  dispatch_async(dispatch_get_main_queue(), ^{
   UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"arguments" message:stirng preferredStyle:UIAlertControllerStyleAlert];
   UIAlertAction * action = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
   }];
   [alertView addAction:action];
   [weakSelf presentViewController:alertView animated:YES completion:nil];
  });
 }; 
}

에서 블록을 정의한 다음 실제로 변환되는 컨텍스트에 저장합니다. 그런 다음 이 함수를 직접 실행하면


에 의해 전달된 매개변수가 [JSContext currentArguments] 배열을 통해 허용됩니다. 이는 JSValue

객체입니다.

OC는 JS

를 호출하여 두 개의 Button을 초기화하고

- (IBAction)callJS:(id)sender {
 [_context evaluatescript:@"showAlert()"];
}
- (IBAction)callJSWithArguments:(id)sender {

 [_context evaluatescript:@"showAlertWithString(&#39;OC call JS with arguments&#39;)"];
// [_context[@"showAlertWithString"] callWithArguments:@[@"OC call JS with arguments"]];
}
클릭

이벤트 JS 호출 OC 구현

요약

위 내용은 OC와 JS 상호작용을 구현하기 위해 JavaScriptCore를 사용한 샘플 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.