您的位置:澳门新葡萄京最大平台 > www.4996.com > UIWebView学习笔记

UIWebView学习笔记

发布时间:2019-09-14 14:48编辑:www.4996.com浏览(115)

    UIWebView学习笔记

    1. iOS 禁止使用webView加载网页的长按出现'拷贝'事件

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
        [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    }
    

    2. iOS webView长按图片,不出现'拷贝'(iOS9默许就是这种意义)

    2.1 准备好JS文件

    // js文件,如:acepack_details.js
    function setImageClickFunction(){
        var imgs = document.getElementsByTagName("img");
        for (var i=0;i<imgs.length;i++){
            imgs[i].style.webkitUserSelect='none';
        }
    }
    

    2.2 注入JS

    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"acepack_details" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil]];
    

    3. webView作为tableView的tableHeaderView

    • 在webView的回调方法里,一定要重复安装tableView的tableHeaderView,不然会并发意料之外的难题。
    -(void)webViewDidFinishLoad:(UIWebView *)webView {
        // 获取到webview的高度
        CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
        self.webView.frame = CGRectMake(self.webView.frame.origin.x, self.webView.frame.origin.y, ScreenWidth, height);
        // 一定要重新设置tableView的tableHeaderView,否则会出现意想不到的问题。
        [self tableView].tableHeaderView = self.webView;
    }
    

    4. 替换webView中的img标签的图片

    • 选取场景
      • 收获页面中装有图片,图片浏览器
      • 非WIFI情形下,加载本地图片
    - (NSString *)replaceImageUrl:(NSString *) content {
        // 匹配<img>标签
        NSString *urlPattern = @"<img[^>]+?src=["']?([^>'"]+)["']?";
        NSError *error = [NSError new];
        NSString *tmp = content;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlPattern options:NSRegularExpressionCaseInsensitive error:&error ];
        // match 这块内容非常强大
        NSUInteger count =[regex numberOfMatchesInString:content options:NSRegularExpressionCaseInsensitive range:NSMakeRange(0, [content length])];// 匹配到的次数
        UIImage *img = [UIImage imageNamed:@"icon_app"];
        // 用网络图片替换webView上显示的图片
        NSString *tmpStr = @"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png";
        // 用本地图片替换webView上显示的图片
        tmpStr = [self htmlForJPGImage:img];
        if(count > 0) {
            NSArray* matches = [regex matchesInString:content options:NSMatchingReportCompletion range:NSMakeRange(0, [content length])];
            for (NSTextCheckingResult *match in matches) {
                NSInteger count = [match numberOfRanges]; // 匹配项
                for(NSInteger index = 0;index < count;index++){
                    NSRange halfRange = [match rangeAtIndex:index];
                    if (index == 1) {
                        // 图片的src属性值
                        NSString *urlStr = [content substringWithRange:halfRange];
                        NSLog(@"=%@=",urlStr);
                        // 保存图片URL
                        [self.imgSrcArrayM addObject:[content substringWithRange:halfRange]];
                        // 替换src属性值
                        tmp = [tmp stringByReplacingOccurrencesOfString:urlStr withString: tmpStr];
                    }
                }
            }
        }
        return tmp;
    }
    
    // 编码图片
    - (NSString *)htmlForJPGImage:(UIImage *)image {
        NSData *imageData = UIImageJPEGRepresentation(image,1.0);
        NSString *imageSource = [NSString stringWithFormat:@"data:image/jpg;base64,%@",[imageData base64Encoding]];
        return imageSource;
    }
    

    5. webView注入JS代码

    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"acepack_details" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil]];
    

    6. webView执行JS代码

    // 调用JS里的setImageClickFunction()函数
    [self.webView stringByEvaluatingJavaScriptFromString:@"setImageClickFunction()"];
    

    7. webView中的图片点击事件

    7.1 准备好JS文件

    // js文件,如:acepack_details.js
    function setImageClickFunction(){
        // 取出所有的img标签
        var imgs = document.getElementsByTagName("img");
        for (var i=0;i<imgs.length;i++){
            var src = imgs[i].src;
            // 绑定事件
            imgs[i].setAttribute("onClick","clickme(src)");
        }
    }
    
    function clickme(imagesrc){
        var url="ClickImage:"+imagesrc;
        document.location = url;
    }
    

    7.2 注入JS

    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"acepack_details" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil]];
    

    7.3 webView央浼回调里,实施JS

    // 调用JS里的setImageClickFunction()函数
    [self.webView stringByEvaluatingJavaScriptFromString:@"setImageClickFunction()"];
    

    7.4 拦截央浼,处理图片的单击事件

    -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)_request navigationType:(UIWebViewNavigationType)navigationType {
        NSString *requestString = [[_request URL] absoluteString];
        NSString *prefix = @"clickimage:";
        if ([requestString hasPrefix:prefix]) {
            DDLogVerbose(@"%@", requestString);
            NSUInteger index = 0;
            NSRange range = [requestString rangeOfString:prefix];
            if (range.location != NSNotFound) {
                NSString *tmpSrc = [requestString substringFromIndex:(range.location + range.length)];
                index = [self.imgSrcArrayM indexOfObject:tmpSrc];
            }
            // 显示图片浏览器
            [self networkImageShow:index];
        }
        return YES;
    }
    

    8. 长按webView上的图样,保存

    8.1 注入JS

    static NSString* const kTouchJavaScriptString=
    @"document.ontouchstart=function(event){
    x=event.targetTouches[0].clientX;
    y=event.targetTouches[0].clientY;
    document.location="myweb:touch:start:"+x+":"+y;};
    document.ontouchmove=function(event){
    x=event.targetTouches[0].clientX;
    y=event.targetTouches[0].clientY;
    document.location="myweb:touch:move:"+x+":"+y;};
    document.ontouchcancel=function(event){
    document.location="myweb:touch:cancel";};
    document.ontouchend=function(event){
    document.location="myweb:touch:end";};";
    [self.webView stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];
    

    8.2 管理点击UIWebView上边的图纸

    #pragma mark - 处理点击UIWebView上面的图片
    - (BOOL)handleWebViewClickImageWithUrl:(NSString *)url{
        NSString *requestString = url;
        NSArray *components = [requestString componentsSeparatedByString:@":"];
        if ([components count] > 1 && [(NSString *)[components objectAtIndex:0]
                                       isEqualToString:@"myweb"]) {
            if([(NSString *)[components objectAtIndex:1] isEqualToString:@"touch"]) {
                //NSLog(@"you are touching!");
                //NSTimeInterval delaytime = Delaytime;
                if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"start"]) {
                    /*
                     @需延时判断是否响应页面内的js...
                     */
                    _gesState = GESTURE_STATE_START;
                    NSLog(@"touch start!");
                    float ptX = [[components objectAtIndex:3]floatValue];
                    float ptY = [[components objectAtIndex:4]floatValue];
                    NSLog(@"touch point (%f, %f)", ptX, ptY);
                    NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", ptX, ptY];
                    NSString *tagName = [self.webView stringByEvaluatingJavaScriptFromString:js];
                    _imgURL = nil;
                    if ([tagName isEqualToString:@"IMG"]) {
                        _imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", ptX, ptY];
                    }
                    if (_imgURL) {
                        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleLongTouch) userInfo:nil repeats:NO];
                    }
                }
                else if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"move"])
                {
                    //**如果touch动作是滑动,则取消hanleLongTouch动作**//
                    _gesState = GESTURE_STATE_MOVE;
                    NSLog(@"you are move");
                }
                else if ([(NSString *)[components objectAtIndex:2]isEqualToString:@"end"]) {
                    [_timer invalidate];
                    _timer = nil;
                    _gesState = GESTURE_STATE_END;
                    NSLog(@"touch end");
                }
            }
            return NO;
        }
        return YES;
    }
    // 处理长按事件
    - (void)handleLongTouch {
        NSLog(@"%@", _imgURL);
        if (_imgURL && _gesState == GESTURE_STATE_START) {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存图片", nil];
            sheet.cancelButtonIndex = sheet.numberOfButtons - 1;
            [sheet showInView:[UIApplication sharedApplication].keyWindow];
        }
    }
    // 弹出对话框
    - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
        if (actionSheet.numberOfButtons - 1 == buttonIndex) return;
        NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
        if ([title isEqualToString:@"保存图片"]) {
            if (_imgURL) {
                NSLog(@"imgurl = %@", _imgURL);
            }
            NSString *urlToSave = [self.webView stringByEvaluatingJavaScriptFromString:_imgURL];
            NSLog(@"image url=%@", urlToSave);
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlToSave]];
            UIImage *image = [UIImage imageWithData:data];
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
    }
    // 回调
    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
        if (error) {
            NSLog(@"Error");
        } else {
            NSLog(@"OK");
        }
    }
    

    9. webView缓存

    9.1 缓存的意义

    1. webView一般是加载UI比较复杂靓丽、可变、iOS原生控件不轻便达成的分界面,所以网页的因素一般都很复杂,对处于GP奥迪Q3S碰着下的客户来讲,流量是个大标题,所以要求缓存!
    2. 当客户处于断网状态下时,为了制止客商步向空白页面,应该把上次已经加载过的页面显示给顾客!
    3. webView的伸手一般都是GET,POST央浼一般是发大量数据给服务器管理(变动性十分的大),因而一般只对GET诉求举行缓存,而不对POST诉求进行缓存。

    9.2 为啥能够开展缓存?

    • NSURLCache在每一种UIWebView的的NSUWranglerLRequest诉求中都会被调用。
    • iOS 5在此之前:只支持内部存款和储蓄器缓存;从iOS 5初阶:同一时候扶助内部存款和储蓄器缓存和硬盘缓存。

    9.3 怎么达成缓存?

    • iOS设备上NSULacrosseLCache暗中同意只能进展内部存款和储蓄器缓存。能够经过子类化NSU逍客LCache来完结自定义的版本进而落成在DISK上缓存内容。
    • 急需重写cachedResponseForRequest,那么些会在呼吁发送前会被调用,从中大家得以确定是或不是对准此NSU哈弗LRequest再次回到本地数据。
    • 要是本地未有缓存就调用下边那条语句:return [super cachedResponseForRequest:request];

    www.4996.com,9.4 NSUSportageLCache常用艺术

    1. 全局缓存对象
    NSURLCache *cache = [NSURLCache sharedURLCache]; 
    
    1. 安装内部存储器缓存的最大容积(字节为单位,默以为512KB)
    -(void)setMemoryCapacity:(NSUInteger)memoryCapacity;
    
    1. 安装硬盘缓存的最大体量(字节为单位,默感觉10M)
    -(void)setDiskCapacity:(NSUInteger)diskCapacity;
    
    1. 获得有个别央求的缓存
    -(NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request; ```
    5. 清除某个请求的缓存
    ``` objc
    -(void)removeCachedResponseForRequest:(NSURLRequest *)request;
    
    1. 排除全体的缓存
    -(void)removeAllCachedResponses;
    

    9.5 设置NSURAV4LRequest缓存战术

    • NSUPAJEROLRequestUseProtocolCachePolicy // 暗中认可的缓存战略(取决于情商)
    • NSU翼虎LRequestReloadIgnoringLocalCacheData // 忽略缓存,重新供给
    • NSURLRequestReloadIgnoringLocalAndRemoteCacheData // 未实现
    • NSUHavalLRequestReloadIgnoringCacheData = NSU奥迪Q7LRequestReloadIgnoringLocalCacheData // 忽略缓存,重新央求
    • NSULacrosseLRequestReturnCacheDataElseLoad // 有缓存就用缓存,未有缓存就再也诉求
    • NSU哈弗LRequestReturnCacheDataDontLoad // 有缓存就用缓存,未有缓存就不发乞求,当做央浼出错管理(用于离线情势)
    • NSURLRequestReloadRevalidatingCacheData // 未实现

    本文由澳门新葡萄京最大平台发布于www.4996.com,转载请注明出处:UIWebView学习笔记

    关键词:

上一篇:只会卑微到尘埃

下一篇:没有了