UIWebView和网页的交互(JS中调用OC代码)
- (void)viewDidLoad
{
[super viewDidLoad];
// 1.webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
{
[super viewDidLoad];
// 1.webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
webView.delegate
=
self;
[self.view
addSubview:webView];
// 2.加载网页
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
// webView每当发送一个请求之前,都会先调用这个方法(能拦截所有请求)
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString *url = request.URL.absoluteString;
NSRange range = [url rangeOfString:@"hm://"];
NSUInteger loc = range.location;
if (loc != NSNotFound) { // url的协议头是hm
// 方法名
NSString *method = [url substringFromIndex:loc + range.length];
// 转成SEL
SEL sel = NSSelectorFromString(method);
[self performSelector:sel withObject:nil];
}
return YES;
}
注意:
1.[webView loadRequest:request];
loadRequest方法,会从网络上加载页面到UIWebView里面。
2.如果JS中调用OC代码,要实现UIWebView的shouldStartLoadWithRequest这个代理方法。
3.request.URL.absoluteString
获取URL的绝对路径
4.rangeOfString判断某一个字符串是否在url中。
5.range.location 获取第一次出现的位置
5.range.location 获取第一次出现的位置