0

I'm trying to add a WKWebView as subview:

func loadWebView() {

    let userAgentStr = self.getUserAgent()
    if let url = URL(string: videoURL.stringValue){
        let request  = URLRequest.init(url: url)
        let config = WKWebViewConfiguration()
        self.webView = WKWebView(frame: self.view.frame, configuration: config)
        self.webView.wantsLayer = true
        self.webView.customUserAgent = userAgentStr
        self.webView.load(request)
        self.webView.layer?.backgroundColor = NSColor.green.cgColor
        self.view.addSubview(self.webView)
        self.view.needsDisplay = true

    }
}

But is not showing in the main NSView. but is been add as a subview:

po self.view.subviews
▿ 9 elements
  - 0 : <NSTextField: 0x10050e400>
  - 1 : <NSTextField: 0x10050f7f0>
  - 2 : <NSTextField: 0x10050e8e0>
  - 3 : <NSButton: 0x600003510000>
  - 4 : <NSButton: 0x6000035100b0>
  - 5 : <NSTextField: 0x10050ee00>
  - 6 : <NSButton: 0x600003510160>
  - 7 : <NSView: 0x6000033054a0>
  - 8 : <WKWebView: 0x600003e01400>

I tried to see if I was doing something wrong and add it a NSView as subview:

func loadNSView() {
    let newView = NSView()
    newView.frame = self.view.frame
    newView.wantsLayer = true
    newView.layer?.backgroundColor = NSColor.white.cgColor
    self.view.addSubview(newView)
    self.view.needsDisplay = true
}

and it work just fine.

Any of you knows what I may be doing wrong ? or what can I do to load the WKWebView ?

I'll really appreciate your help.

matt
  • 447,615
  • 74
  • 748
  • 977
user2924482
  • 6,844
  • 16
  • 65
  • 133
  • 1
    This is probably irrelevant, but it is almost never right to say `self.webView = WKWebView(frame: self.view.frame)`. You mean `self.webView = WKWebView(frame: self.view.bounds)`. – matt Apr 11 '19 at 23:41
  • @matt I tried `self.webView = WKWebView(frame: self.view.bounds, configuration: config)` but didn't do the trick – user2924482 Apr 12 '19 at 01:40
  • No, I said it was probably irrelevant. :) But still, it’s important to get into the right habits. — Let’s work on your actual problem. Could you experiment? Instead of `self.webView.load(request)`, does it make things any better if you say `delay(2) {self.webView.load(request)}`? (My `delay` function is [here](https://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861).) I ask because if it does, it suggests that trying to load a request into a web view before it is truly in the interface might be the problem. – matt Apr 12 '19 at 01:53
  • @matt, no changes. still not showing the webView. – user2924482 Apr 12 '19 at 03:06

1 Answers1

0

I found the root of this issue. Since is MacOS (Cocoa) app you need to enable incoming and outgoing connections:

enter image description here

user2924482
  • 6,844
  • 16
  • 65
  • 133