ios swift wkwebview

WKWebView displays content wrong after orientation change

I am fairly new to iOS development and I’m using a WKWebView to display a page that plays a video using the Vimeo Player. When the app starts up, it shows the view correctly, no matter what orientation it is currently in. However, once I change the orientation the view will either look zoomed in or has whitespace below the video.

The annoying thing about this is that it’s not consistent. Sometimes the view displays correctly, sometimes it doesn’t. If I try to zoom the view in or out or try to scroll when using the app it usually corrects itself, but even that does not seem to be 100% reliable.

Some screenshots (tested on iPad 2):

Landscape orientation (correct):
Landscape orientation (correct)

Portrait orientation (correct):
Portrait orientation (correct)

Landscape orientation (incorrect):
Landscape orientation (incorrect)

Portrait orientation (incorrect):
Portrait orientation (incorrect)

And the code used to produce this result:

import Foundation
import UIKit
import WebKit
class VideoViewController : UIViewController, WKScriptMessageHandler {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func loadView() {
self.webView = WKWebView()
let contentController = WKUserContentController();
let scaleToFit = WKUserScript(source: "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, initial-scale=1.0'); document.getElementsByTagName('head')[0].appendChild(meta);", injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true)
contentController.addScriptMessageHandler(self, name: "callbackHandler")
self.view = webView!
override func viewDidLoad() {
override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.
func refreshUI() {
let url = NSURL(string: "")
let requestObj = NSURLRequest(URL: url!)
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if( == "callbackHandler") {
print("JavaScript is sending a message \(message.body)")

I looked through SO for WKWebView and orientation change and didn’t find anything that helped me.

Your help is appreciated.