UIWebView与JS的交互

本文介绍了一个iOS应用中如何使用UIWebView加载网页,并实现与JavaScript的交互。具体包括UIWebView的初始化、网页请求过程及如何监听JavaScript触发的动作。

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

@interface ViewController ()<UIWebViewDelegate>
@property(nonatomic,strong)UIWebView *webView;
@end
- (void)viewDidLoad
{
    [super viewDidLoad];
  //创建对象
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 460)];

    //请求数据
    //1.生成一个网址
    NSString *path = @"http://www...";

    //2.将网址放入NSURL对象  名称:统一资源定位器
    NSURL *url = [NSURL URLWithString:path];

    //3.请求数据的对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [_webView loadRequest:request];//通过webView加载数据(请求数据)
    _webView.delegate = self;
    [self.view addSubview:_webView];

}

pragma mark UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{//html页面的js动作触发时运行
 NSString * str = [[request URL] absoluteString];//获取请求的绝对路径.

    //将UTF8字符转化为string:stringByReplacingPercentEscapesUsingEncoding  字符串转为UTF8:stringByAddingPercentEscapesUsingEncoding
NSString *urlStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 NSArray *array = [urlStr componentsSeparatedByString:@"?"];//用?来截取字符串

if (array.count>=2) {
        if ([[NSString stringWithFormat:@"%@",array[1]] hasPrefix:@"/msg"]) {
        }else
        {             

    }

    return YES;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值