JavaScript与OC交互

[[[UIWebView alloc] init] stringByEvaluatingJavaScriptFromString:@"alert(100);"];//oc直接运行js代码
  • html代码




第一个网页











  • OC代码

    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
      // url == JavaScript://sendMessage_?200
      NSString *url = request.URL.absoluteString;
      NSString *scheme = @"JavaScript://";
      if ([url hasPrefix:scheme]) {
          // 获得协议后面的路径  path == sendMessage_number2_?200&300
          NSString *path = [url substringFromIndex:scheme.length];
          // 利用?切割路径
          NSArray *subpaths = [path componentsSeparatedByString:@"?"];
          // 方法名 methodName == sendMessage:number2:
          NSString *methodName = [[subpaths firstObject] stringByReplacingOccurrencesOfString:@"_" withString:@":"];
          // 参数  200&300
          NSArray *params = nil;
          if (subpaths.count == 2) {
              params = [[subpaths lastObject] componentsSeparatedByString:@"&"];
          }
          // 调用
          [self performSelector:NSSelectorFromString(methodName) withObjects:params];
          
          return NO;
      }
      
      NSLog(@"想加载其他请求,不是想调用OC的方法");
      
      return YES;
    }
    
    - (id)performSelector:(SEL)selector withObjects:(NSArray *)objects
    {
      // 方法签名(方法的描述)
      NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
      if (signature == nil) {
          [NSException raise:@"错误" format:@"%@方法找不到", NSStringFromSelector(selector)];
      }
      
      // NSInvocation : 利用一个NSInvocation对象包装一次方法调用(方法调用者、方法名、方法参数、方法返回值)
      NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
      invocation.target = self;
      invocation.selector = selector;
      
      // 设置参数
      NSInteger paramsCount = signature.numberOfArguments - 2; // 除self、_cmd以外的参数个数
      paramsCount = MIN(paramsCount, objects.count);
      for (NSInteger i = 0; i < paramsCount; i++) {
          id object = objects[i];
          if ([object isKindOfClass:[NSNull class]]) continue;
          [invocation setArgument:&object atIndex:i + 2];
      }
      
      // 调用方法
      [invocation invoke];
      
      // 获取返回值
      id returnValue = nil;
      if (signature.methodReturnLength) { // 有返回值类型,才去获得返回值
          [invocation getReturnValue:&returnValue];
      }
      
      return returnValue;
    }
    - (void)sendMessage:(NSString *)number number2:(NSString *)number2 number3:(NSString *)number3
     {
     NSLog(@"%s %@ %@ %@", __func__, number, number2, number3);
     }
    

你可能感兴趣的:(JavaScript与OC交互)