Swift WKWebView doesn’t get initialised

I’m trying to get a rich text editor for iOS in Swift working. I do however get the following error:


Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value


When running this piece of code:


public var text: String? {
    didSet {
        guard let text = text else { return }
        if editorView.isLoading {
            textToLoad = text
        } else {
            editorView.evaluateJavaScript("richeditor.insertText("(text.htmlEscapeQuotes)");", completionHandler: nil)
            placeholderLabel.isHidden = !text.htmlToPlainText.isEmpty


The error appears at line 04.

This is why I suppose that the editorView doesn’t get initialised. It should however be as you can see in the init method:


private var editorView: WKWebView!
  public override init(frame: CGRect = .zero) {

      placeholderLabel.textColor = UIColor.lightGray.withAlphaComponent(0.65)

      guard let bundlePath = Bundle(for: type(of: self)).path(forResource: "Resources", ofType: "bundle"),
          let bundle = Bundle(path: bundlePath),
          let scriptPath = bundle.path(forResource: "RichTextEditor", ofType: "js"),
          let scriptContent = try? String(contentsOfFile: scriptPath, encoding: String.Encoding.utf8),
          let htmlPath = bundle.path(forResource: "RichTextEditor", ofType: "html"),
          let html = try? String(contentsOfFile: htmlPath, encoding: String.Encoding.utf8)
          else { fatalError("Unable to find javscript/html for text editor") }

      let configuration = WKWebViewConfiguration()
          WKUserScript(source: scriptContent,
                      injectionTime: .atDocumentEnd,
                      forMainFrameOnly: true

      editorView = WKWebView(frame: .zero, configuration: configuration)

      super.init(frame: frame)

      [RichTextEditor.textDidChange, RichTextEditor.heightDidChange].forEach {
          configuration.userContentController.add(WeakScriptMessageHandler(delegate: self), name: $0)

      editorView.navigationDelegate = self
      editorView.scrollView.delegate = self



      editorView.translatesAutoresizingMaskIntoConstraints = false

      editorView.loadHTMLString(html, baseURL: nil)



The class in which this happens has the following signature:



public class RichTextEditor: UIView, WKScriptMessageHandler, WKNavigationDelegate, UIScrollViewDelegate {



Any input on how I can fix this issue is welcome! Thanks.

Powered by WPeMatico

You may also like...

Comments are closed.