转自:http://www.cnblogs.com/gcb999/p/3178728.html
框架:
webview与js的通信框架
#import "MJViewController.h" #import "MBProgressHUD+Add.h" @interface MJViewController () @end @implementation MJViewController - (void)viewDidLoad { [super viewDidLoad]; [self loadRemoteHTML]; } #pragma mark 加载远程的HTML页面 - (void)loadRemoteHTML { NSURL *url = [NSURL URLWithString:@"http://192.168.1.106:8080/MJServer/"]; self.webView.delegate = self; [self.webView loadRequest:[NSURLRequest requestWithURL:url]]; } #pragma mark 加载其他文件 - (void)loadRemoteTxt { NSURL *url = [NSURL URLWithString:@"http://192.168.1.106:8080/MJServer/abc.txt"]; self.webView.delegate = self; [self.webView loadRequest:[NSURLRequest requestWithURL:url]]; } #pragma mark 加载PDF文件 - (void)loadLocalPDF { //[self.webView loadData:<#(NSData *)#> MIMEType:<#(NSString *)#> textEncodingName:<#(NSString *)#> baseURL:<#(NSURL *)#>]; NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Desktop/第10章-网络.pdf"]; self.webView.delegate = self; [self.webView loadRequest:[NSURLRequest requestWithURL:url]]; } #pragma mark 加载HTML字符串 - (void)loadHTMLString { NSURL *url = [NSURL fileURLWithPath:@"/Users/apple/Pictures"]; [self.webView loadHTMLString:@"<html><body><img src=‘lufy.png‘></body></html>" baseURL:url]; } #pragma mark - webview代理方法 - (void)webViewDidStartLoad:(UIWebView *)webView { NSLog(@"开始加载页面"); [MBProgressHUD showMessag:@"哥正在帮你加载..." toView:self.view]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"页面加载完毕"); [MBProgressHUD hideHUDForView:self.view animated:YES]; self.backItem.enabled = self.webView.canGoBack; self.forawrdItem.enabled = self.webView.canGoForward; self.titleItem.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"]; //[self.webView stringByEvaluatingJavaScriptFromString:@"fn();"]; } #pragma mark webview每次加载之前都会调用这个方法 // 如果返回NO,代表不允许加载这个请求 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { // 说明协议头是ios if ([@"ios" isEqualToString:request.URL.scheme]) { NSString *url = request.URL.absoluteString; NSRange range = [url rangeOfString:@":"]; NSString *method = [request.URL.absoluteString substringFromIndex:range.location + 1]; SEL selector = NSSelectorFromString(method); if ([self respondsToSelector:selector]) { [self performSelector:selector]; } return NO; } return YES; } #pragma mark - 提供一个接口方法给JS调用 - (void)openCamera { NSLog(@"打开了照相机"); } - (void)call { NSLog(@"打电话"); } #pragma mark - 按钮方法 #pragma mark 前进 - (void)forawrd { [self.webView goForward]; } #pragma mark 后退 - (void)back { [self.webView goBack]; } @end
服务端的用法
时间: 2024-12-12 23:19:35