Search code examples
iosswiftwebkitalamofirewkwebview

Download document & Load Image(png, jpeg), pdf, doc, etc in WKWebView swift


I am using Alamofire to download documents from a url, the document can be image, pdf or doc etc. Below code is used to download using Alamofire and saving in the document directory and loading in webview.

func saveToDocumentDirectory(BillUrl: String) {
        let manager = Alamofire.Session.default
        let fileName = (BillUrl.components(separatedBy: "/").last) ?? ""
        MBProgressHUD.showAdded(to: self.view, animated: true)

        let destinationPath: DownloadRequest.Destination = { _, _ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0];
            let fileURL = documentsURL.appendingPathComponent(fileName)
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        manager.download(BillUrl, method: .get, parameters: nil, headers: nil, to: destinationPath)
            .downloadProgress { (progress) in
                print("Temporary URL: ")
                print(progress.fractionCompleted)
        }
        .response { response in
            switch response.result {
            case .success(let pathUrl) :
                MBProgressHUD.hide(for: self.view, animated: true)
                print(pathUrl as Any)  //pathUrl = file:///var/mobile/Containers/Data/Application/C651C521-31A7-4512-A393-6A94442472A0/Documents/1_DlatFlsbZ1fJSs-_aIJmlg_1588075057_13.png

                self.displayAlert(path: pathUrl ?? URL(string: "")!)

            case .failure(let error) :
                MBProgressHUD.hide(for: self.view, animated: true)
                print(error)
                self.alert(message: "Something went wrong while proccessing your request", title: "Alert!")
            }
        }
    }

    fileprivate func displayAlert(path: URL) {
        let alertController = UIAlertController(title: "Alert!", message: "file downloaded at \(path)", preferredStyle: .alert)
        let OKAction = UIAlertAction(title: "OK", style: .default, handler: { action in  
            let webViewVC = storyBoard.instantiateViewController(withIdentifier: "WebViewVC") as! WebViewVC
            webViewVC.webUrl = path
            self.navigationController?.pushViewController(webViewVC, animated: true)
        })
        alertController.addAction(OKAction)
        self.present(alertController, animated: true, completion: nil)
    }

below code for webview class

class WebViewVC: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!
    var webUrl = URL(string: "")

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.isHidden = false
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        webView.allowsBackForwardNavigationGestures = true
        webView.autoresizesSubviews = true
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        webView.load(URLRequest(url: webUrl!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 600.0))
    }

    override func viewDidLayoutSubviews() {
        webView.frame = CGRect.init(x: 0, y: 0, width: self.view.frame.size.width , height: self.view.frame.size.height)
        view = webView
    }
}

The pdf file is loading properly in webview, but the image is not loading properly in webview and the top part of image hiding behind the navigation bar. enter image description here enter image description here

I created the outlet of WKWebView and also adding it to self.view.addSubview(webView) but every time it get crashed at webView = WKWebView(frame: .zero, configuration: webConfiguration) I don't know what to try next. Thank you in advance.


Solution

  • We can create the WKWebView by setting the frame so that it does not overlap with UINavigationBar.

    import UIKit
    import WebKit
    
    class SecondViewController: UIViewController,UIWebViewDelegate,UIScrollViewDelegate, WKUIDelegate {
    
       var WKwebView: WKWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
                   let userContentController: WKUserContentController = WKUserContentController()
                   let conf = WKWebViewConfiguration()
                   conf.userContentController = userContentController
                   WKwebView = WKWebView (frame: CGRect( x: 0, y: 60, width: self.view.frame.width, height: self.view.frame.height - 60 ), configuration: WKWebViewConfiguration())
                   WKwebView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                   WKwebView.uiDelegate = self
                   WKwebView.scrollView.bounces = false
                   WKwebView.scrollView.delegate = self;
                   view.addSubview(WKwebView)
    
                    var request : URLRequest!
                    let LOGINURL = "https://i.sstatic.net/RRy76.png";
                    let url : URL = URL(string: LOGINURL as String)!
                    request = URLRequest (url: url);
                    WKwebView.load(request)
    
        }
    }
    

    Output : Output without overlapping