Reputation: 70946
I have a UIWebView
in my app and I'm attempting to use loadHTMLString(_:, baseURL:)
to load HTML that's stored in a String
in the app. The web view always shows up as a plain gray rectangle with no content. If I save the HTML string to a file and load it in Safari on my Mac, the page renders as expected.
I thought maybe it was something about the HTML so I've reduced it to a minimal test that gets the same results:
let myHTMLString = "<html><head></head><body><p>This is a test</p></body></html>"
myWebView.loadHTMLString(myHTMLString, baseURL: nil)
Still a gray rectangle.
I've browsed other answers here to check and verify various possibly-relevant details:
UIWebView
. All of the content is there, it's just not visible in the iOS app.UIWebView
delegate methods and set the delegate property. I get calls to webViewDidStartLoad(_:)
, webViewDidFinishLoad(_:)
, and webView(_:shouldStartLoadWith:navigationType:)
, and in the last case I always return true
. No error is reported-- I never get a webView(_:didFailLoadWithError:)
.UIWebView
I get a different color of rectangle but I still don't get any visible page content.What have I missed? This should be a trivial case but I get no visible content.
Upvotes: 2
Views: 1830
Reputation: 70946
After investigating and trying a new project (inspired by @DonMag's answer), it looks like the problem is that the UIWebView
was contained in a UIStackView
. Although the web view's dimensions were correct, this somehow prevented it from rendering content. I've tried this in a simple test project and the behavior carries over-- a plain UIWebView
on its own works fine, but one contained in a stack view doesn't render its content, even if its size is correct.
I don't know why that is or whether there's a trick I could use to get a web view to work correctly within a stack view. But the cause is clear, if not the reason.
Upvotes: 1
Reputation: 77462
Try a fresh, empty UIViewController, with only this as the code:
import UIKit
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let newWebView = UIWebView(frame: CGRect(x: 8, y: 8, width: 300, height: 400))
self.view.addSubview(newWebView)
// cyan background html
let myHTMLString = "<html><head></head><body bgcolor=#00ffff><p>This is a test</p></body></html>"
newWebView.loadHTMLString(myHTMLString, baseURL: nil)
}
}
Upvotes: 1
Reputation: 268
It's quite odd the error you're getting, but have you already tried to set a value for baseURL
parameter? Something like: URL(string: "www.google.com")
Upvotes: 1