UIWebView和网页的交互(JS中调用OC代码)

本文介绍如何在iOS应用中使用UIWebView加载本地HTML文件,并通过JavaScript调用Objective-C (OC) 方法实现与UIWebView的交互。文章重点讲解了shouldStartLoadWithRequest代理方法的应用,用于拦截和处理特定协议头的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UIWebView和网页的交互(JS中调用OC代码)
- (void)viewDidLoad
{
    [
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代码,要实现UIWebViewshouldStartLoadWithRequest这个代理方法。
3.request.URL.absoluteString 获取URL的绝对路径
4.rangeOfString判断某一个字符串是否在url中。
5.range.location 获取第一次出现的位置


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值