Skip to content

Instantly share code, notes, and snippets.

@yannickl
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save yannickl/4a3a11073d3cedf7e7ec to your computer and use it in GitHub Desktop.

Select an option

Save yannickl/4a3a11073d3cedf7e7ec to your computer and use it in GitHub Desktop.

Revisions

  1. yannickl renamed this gist Oct 7, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. yannickl created this gist Oct 7, 2014.
    46 changes: 46 additions & 0 deletions Example
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    //
    // ViewController.swift
    // TestWKWebView
    //
    // Created by Yannick Loriot on 01/10/14.
    // Copyright (c) 2014 Yannick Loriot. All rights reserved.
    //

    import UIKit
    import WebKit

    let htmlContent = "<!DOCTYPE html><html><head><script>webkit.messageHandlers.event.postMessage('message 1'); setTimeout(function() { webkit.messageHandlers.event.postMessage('message 2'); }, 2000);</script></head></html>"

    class MyObject: NSObject, WKScriptMessageHandler {
    var webView: WKWebView

    override init() {
    var config = WKWebViewConfiguration()

    webView = WKWebView(frame: CGRectZero, configuration: config)
    webView.loadHTMLString(htmlContent, baseURL: nil)

    super.init()

    config.userContentController.addScriptMessageHandler(self, name: "event")
    }

    // MARK: - WKScriptMessageHandler Methods

    func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!) {
    println("\(message.name) received: \(message.body)")
    }
    }

    class ViewController: UIViewController {
    var strongObject: MyObject?

    override func viewDidLoad() {
    super.viewDidLoad()

    strongObject = MyObject()

    // Everything is OK with the simulator but if I comment the line below it does not work on my iPad Mini Retina (iOS 8.0.2)
    view.addSubview(strongObject!.webView)
    }
    }