在HTML中调用iOS
2016-10-14 14:31 甘雨路 阅读(852) 评论(0) 编辑 收藏 举报<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <button style="width:120px; height = 60px;" onclick="getImage();">插入图片</button> <script> function getImage(){ // 生成接口(在OC在截取接口) window.location.href = 'lf://getImage'; } </script> </body> </html>
#import "ViewController.h" @interface ViewController ()<UIWebViewDelegate> @property (nonatomic , strong) UIWebView *webView; @property (nonatomic , copy) NSString *isIncreaseImg; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 初始化webView self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height)]; self.webView.delegate = self; [self.view addSubview:self.webView]; // 加载本地网页 NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; [self.webView loadRequest:request]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ // 截取接口 NSString *str = request.URL.absoluteString; NSRange range = [str rangeOfString:@"lf://"]; // 如果发现接口,则执行相关操作 if (range.location != NSNotFound) { [self htmlCallOC]; } return YES; } #pragma mark -- 操作网页 -- - (void)webViewDidFinishLoad:(UIWebView *)webView{ // 插入图片 if([self.isIncreaseImg isEqualToString:@"incareaseImage"]){ NSString *str4 = @"var img = document.createElement('img');" "img.src = 'ply.png';" "document.body.appendChild(img);"; [webView stringByEvaluatingJavaScriptFromString:str4]; self.isIncreaseImg = @"imageIsInceased"; }else{ NSLog(@"%@",self.isIncreaseImg); } } #pragma mark -- 执行相关操作 -- - (void)htmlCallOC{ NSLog(@"HTML成功调用OC"); if (self.isIncreaseImg ==nil) { self.isIncreaseImg = @"incareaseImage"; } [self webViewDidFinishLoad:self.webView]; } @end