Swift3.0之WebView实现网页中图片预览

Swift3.0之WebView实现网页中图片预览_第1张图片
效果图

//利用UIWebViewDelegate实现截取网页中的图片
extension ViewController:UIWebViewDelegate{
   
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    //这个方法是获取网页中的所有图片
    //这里是js,主要目的实现对url的获取
        let getImg = "function getImages(){ " +
            "var objs = document.getElementsByTagName(\"img\");" +
            "var imgScr = '';" +
            "for(var i=0;i Bool {
        
        
        let requestString:String = (request.url?.absoluteString)!
        
        
        let scheme = "hyb-image-preview:"
        
        if requestString.hasPrefix(scheme) {
            // 获取原始图片的URL
            
            let path:String = (request.url?.absoluteString.substring(from: scheme.endIndex))!
            //            let src = request.url?.absoluteString.replacingOccurrences(of: scheme, with: "")
            //
            //            print(src)
            
            showBigImage(imageUrl: path)
            
            return false
            
        }
        
        
        return true
        
    }
    
//接收并展示图片 
    func showBigImage(imageUrl:String)   {
        

//一定要写这一句,不然只能预览一次图片
        self.bgView.isHidden = false
        
        self.view.addSubview(self.bgView)
        
        
        bgView.backgroundColor = UIColor(red:0.3 , green: 0.3, blue: 0.3, alpha: 0.7)
        
        
        
        let imageView = UIImageView(frame: CGRect(x: 0, y: SCREENW/2, width: SCREENW, height: 240))
        
        imageView.isUserInteractionEnabled = true
        
        imageView.cz_setImage(urlString:imageUrl, placeholderImage: nil)
        
        
        self.bgView.addSubview(imageView)
        
        
        self.bgView.addOnClickListener(target: self, action: #selector(closeClick))
        
        bgView.addSubview(closeBtn)  
    }
    
     //关闭图片
    
    func closeClick()  {
        
        
        self.bgView.isHidden = true
        
        
    }

    
}

你可能感兴趣的:(Swift3.0之WebView实现网页中图片预览)