欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS【webView 加载微信文章注入JS实现交互 浏览图片及保存】

程序员文章站 2022-04-07 19:34:18
iOS【webView 加载微信文章注入JS实现交互 浏览图片及保存】。最近项目某个模块中要求可以实现对网页中图片的查看,并要求在多张图片的情况下可以实现滑动浏览。 所以,问题的...

iOS【webView 加载微信文章注入JS实现交互 浏览图片及保存】。最近项目某个模块中要求可以实现对网页中图片的查看,并要求在多张图片的情况下可以实现滑动浏览。
所以,问题的集中点就是如何获取所有的图片地址及添加图片的点击事件。不多说,直接上码!

在网页加载完成时,通过js获取图片和添加点击的识别方式

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [IDProgressHUD IDPlaceViewHideDirect:self.view];

    //这里是js,主要目的实现对url的获取
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i<objs.length;i&#43;&#43;){\ imgscr="imgScr" &#43;="" objs[i].src="" '&#43;';\="" };\="" return="" imgscr;\="" };";="" [webview="" stringbyevaluatingjavascriptfromstring:jsgetimages];="" 注入js方法="" nsstring="" *urlresurlt="[webView" stringbyevaluatingjavascriptfromstring:@"getimages()"];="" murlarray="[NSMutableArray" arraywitharray:[urlresurlt="" componentsseparatedbystring:@"&#43;"]];="" if="" (murlarray.count="">= 2) {
        [mUrlArray removeLastObject];
    }
    //urlResurlt 就是获取到得所有图片的url的拼接;mUrlArray就是所有Url的数组

    //添加图片可点击js
    [mWebView stringByEvaluatingJavaScriptFromString:@"function registerImageClickAction(){\
     var imgs=document.getElementsByTagName('img');\
     var length=imgs.length;\
     for(var i=0;i<length;i&#43;&#43;){\ img="imgs[i];\" img.onclick="function(){\" window.location.href="image-preview:" &#43;this.src}\="" }\="" }"];="" [mwebview="" stringbyevaluatingjavascriptfromstring:@"registerimageclickaction();"];="" }="" 

//在这个方法中捕获到图片的点击事件和被点击图片的url

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    //预览图片
    if ([request.URL.scheme isEqualToString:@"image-preview"]) {
        NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //path 就是被点击图片的url
        return NO;
    }
    return YES;
}
以下是保存所在作用域的图片
    //添加长按事件
    UILongPressGestureRecognizer *longPressed = [[UILongPressGestureRecognizer alloc]
                                                 initWithTarget:self action:@selector(longPressed:)];
    longPressed.minimumPressDuration = 0.3;
    longPressed.delegate = self;
    [webView addGestureRecognizer:longPressed];

    /**
 获取长按事件所在的位置图片
 */
- (void)longPressed:(UILongPressGestureRecognizer*)recognizer
{
    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }
    CGPoint touchPoint = [recognizer locationInView:_webView];
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src",
                        touchPoint.x, touchPoint.y];
    NSString *webImage = [_webView stringByEvaluatingJavaScriptFromString:imgURL];

    if([webImage rangeOfString:@"player"].location !=NSNotFound || webImage.length == 0){
        return;
    }
    [self showImageOptionsWithUrl:webImage];
}

- (void)showImageOptionsWithUrl:(NSString *)imageUrl
{
    _webImageURL = imageUrl;
    IBActionSheet *standardIBAS = [[IBActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"保存图片" otherButtonTitles:nil];
    [standardIBAS setFont:FontWithSize(SIZE_FONT_CONTENT)];
    [standardIBAS setTitleFont:FontWithSize(SIZE_FONT_SUBCONTENT)];
    [standardIBAS setButtonTextColor:[UIColor blackColor]];
    [standardIBAS showInView:self.navigationController.view];
}


#pragma mark - IBActionSheetDelegate

-(void)actionSheet:(IBActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 0) {

        NSURL *url = [NSURL URLWithString:_webImageURL];
        NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue new]];
        NSURLRequest *imgRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];

        NSURLSessionDownloadTask  *task = [session downloadTaskWithRequest:imgRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                return ;
            }
            NSData * imageData = [NSData dataWithContentsOfURL:location];
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImage * image = [UIImage imageWithData:imageData];
                UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
            });   
        }];
        [task resume];
    }
}

后记:js挺好玩,我相信以后还会去多接触它。