WKWebView fails to load images and CSS using loadHTMLString(_, baseURL:)

前端 未结 10 821
抹茶落季
抹茶落季 2020-12-14 14:05

Apple\'s recommendation:

In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView.

Thus, I have r

10条回答
  •  無奈伤痛
    2020-12-14 14:36

    Without taking a look at your actual project it's difficult to give some hundreed percent sure advices.

    However:

    class ViewController: UIViewController {
    
        var webView = WKWebView()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            webView.translatesAutoresizingMaskIntoConstraints = false
            let views = [
                "webView" : webView
            ]
            view.addSubview(webView)
            var constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: [.AlignAllLeading, .AlignAllTrailing], metrics: nil, views: views)
            constraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: [.AlignAllTop, .AlignAllBottom], metrics: nil, views: views))
            NSLayoutConstraint.activateConstraints(constraints)
    
            let path = NSBundle.mainBundle().pathForResource("ios - WKWebView fails to load images and CSS using loadHTMLString(_, baseURL_) - Stack Overflow", ofType: "htm")
            let url = NSURL(fileURLWithPath: path!)
            webView.loadHTMLString(try! String(contentsOfURL: url), baseURL: url.URLByDeletingLastPathComponent)
    
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    }
    

    I think the key point here is baseUrl parameter, you should setup it correctly. In my case i've used html's url without last path component - e.g. containing folder. This works fine on both device & simulator - check device snapshot. I've uploaded sample project to https://github.com/soxjke/WKWebViewTest so you can take a look (i've removed codesigning info from git)

    So, to recap - method is working, functionality is working, just you do something wrong with it. To help you get what's wrong with your solutions, i'll add some suggestions: 1. Remember, that simulator filesystem is case-insensitive, device filesystem is case-sensitive. So if you have your filenames in html in lowercase - this won't work on device. 8fFsD.png != 8ffsd.png 2. Remember, that when copying resources, XCode ignores your folder structure. So if your html has and your XCOde project has folder structure like

    test.htm
    
    img/
    
        1.png 
        2.png
    

    After build it will be flattened, so test.htm and 1.png and 2.png will reside on same level

    test.htm
    1.png 
    2.png
    

    I'm almost sure, after you verify these two assumptions, you'll get this method working.

提交回复
热议问题