JS中调用OC
1 #import "ViewController.h" 2 3 @interface ViewController () <UIWebViewDelegate> 4 @end 5 6 @implementation ViewController 7 8 - (void)viewDidLoad 9 { 10 [super viewDidLoad]; 11 // 1.webView 12 UIWebView *webView = [[UIWebView alloc] init]; 13 webView.frame = self.view.bounds; 14 webView.delegate = self; 15 [self.view addSubview:webView]; 16 17 // 2.加载网页 18 NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]; 19 NSURLRequest *request = [NSURLRequest requestWithURL:url]; 20 [webView loadRequest:request]; 21 } 22 23 #pragma mark - UIWebViewDelegate 24 - (void)webViewDidFinishLoad:(UIWebView *)webView 25 { 26 27 } 28 29 /** 30 * webView每当发送一个请求之前,都会先调用这个方法(能拦截所有请求) 31 */ 32 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 33 { 34 NSString *url = request.URL.absoluteString; 35 NSRange range = [url rangeOfString:@"hm://"]; 36 NSUInteger loc = range.location; 37 if (loc != NSNotFound) { // url的协议头是hm,也可以随便起 38 // 方法名 39 NSString *method = [url substringFromIndex:loc + range.length]; 40 41 // 转成SEL 42 // SEL sel = NSSelectorFromString(method); 43 // [self performSelector:sel withObject:nil]; 44 [self performSelector:NSSelectorFromString(method) withObject:nil]; 45 } 46 return YES; 47 } 48 49 /** 50 * 打电话 51 */ 52 - (void)call 53 { 54 NSLog(@"call----"); 55 } 56 57 /** 58 * 打开照相机 59 */ 60 - (void)openCamera 61 { 62 NSLog(@"openCamera----"); 63 } 64 65 @end
HTML网页代码图