iOS js交互(OC)

来源:互联网 发布:淘宝每日精选怎么加入 编辑:程序博客网 时间:2024/06/05 19:22

1.先加载html文件

NSString *mainBundleDirectory=[[NSBundle mainBundle] bundlePath];        NSString *path=[mainBundleDirectory stringByAppendingPathComponent:docName]; //docName是html的名字如@"aa.html"        NSURL *url=[NSURL fileURLWithPath:path];        request=[NSURLRequest requestWithURL:url];[self.webView loadRequest:request];


2.OC代码调用js方法

    a->将数据转换成能传给js的字符串

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object                                                       options:NSJSONWritingPrettyPrinted                                                          error:&error];_content = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    b->调用js的方法

[_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"initA(%@,1)",_content]];  //initA是JS中的方法

3.js调用OC方法
    在UIWebViewDelegate的方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
    中写,被js调用的方法,应为每次加载请求的时候都会调用这个方法
NSString *requestString = [[request URL] absoluteString]; //获取请求的链接地址//当js中调用downloaddata://请求时掉用系统方法if([requestString hasPrefix:@"downloaddata://"]){    //调用OC的方法}


4.点击网页上的图片放大

    在UIWebViewDelegate的方法

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
    中写,被js调用的方法,应为每次加载请求的时候都会调用这个方法

    //@"image-Prefix:http://。。。"]];//点击图片后js返回的地址            if ([request.URL.scheme isEqualToString:@"image-Prefix"]) {        NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-image-Prefix:" length]];        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];                //path就是图片的链接,可以进行相关操作                return NO;    }

0 0