Abdalla AlHaj Hasan Abdalla AlHaj Hasan - 1 month ago 9
Swift Question

Why WKWebView doesn't display videos? - Swift 3

I successfully added a

WKWebView
programmatically In a
viewController
(in
viewDidLoad()
). When loading a url that contains a video it appears fine, but when I try to tap on it (playing it), I cannot see it, but the audio works fine.

The weird thing is I created a new project just to make sure it should works fine and it did, I copied the same exact code the webView displayed the video as it should.

It was working fine before converting to Swift 3.

This is how it looks when tapping on the video:

Before tapping:

enter image description here

After Tapping:

enter image description here

I also tried another web page:

Before tapping:

enter image description here

After Tapping (Note that the status bar is hidden now):

enter image description here

Simply, this is the code:

override func viewDidLoad() {
super.viewDidLoad()

let web = WKWebView(frame: view.frame)
let urlRequest = URLRequest(url: URL(string: "http://www.w3schools.com/html/html5_video.asp")!)
web.frame = view.frame
web.load(urlRequest)

view.addSubview(web)
}


I tried to check many cases without any output. What am I missing?

Thanks in advance.

Answer

I think the video is playing behind your WKWebview, could you please debug the view hierarchy and post it? Xcode->Menu->Debug->View Debugging->Capture View Hierarchy when playing the video.

I've tried with a new swift3 project and with your code, there is no problem, here is the view hierarchy:

enter image description here

You can see that from left pannel, the AVPlayerView is in another UIWindow, different from WKWebView,So I guess the UIWindow which contains the WKWebView in your project has a higher windowLevel so it shows above the UIWindow which contains AVPlayer.

And by making the default UIWindow a higher WindowLevel(UIWindowLevelAlert),I reproduced what you've seen in your project.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    window?.windowLevel = UIWindowLevelAlert
    return true
}