How can I get javascript console.log to println() to the Xcode debugger in Swift?

Is there a way to show javascript errors and/or console logs to the debugger in Xcode using swift? If so, how?

3 thoughts on “How can I get javascript console.log to println() to the Xcode debugger in Swift?”

  1. If you have set up a proper connection between your javascript and swift code (using for example the method here: http://www.kinderas.com/technology/2014/6/15/wkwebview-and-javascript-in-ios-8-using-swift) you can just write a method in JS which sends a message to a designated scriptMessageHandler in swift which then println to xcode output.

    Something like this (hastily written, might be a typos)

    JS method sending to swift:

    function sendConsole(message) {
        try {
            webkit.messageHandlers.myMessageHandler.postMessage("Console:" + message);
        } catch(err) {
            console.log('Something is wrong');
        }
    }
    

    Extract of the swift code to handle it:

    func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
    
        if(message.name == "myMessageHandler") {
            println(message.body)
        } 
    }
    

    If you are unsure how to do this follow the link, he does an excellent job of explaining it.

    Reply
  2. You can use Desktop Safari Develop tools.

    1. Run Xcode simulator.
    2. Open Desktop Safari develop tool, Safari menu bar -> Develop -> Simulator -> Choose your Xcode simulator app name. Then a Web Inspector shows.
    3. All console.log message will be printed on the Web Inspector when you run the Xcode simulator.

    To show Develop tools on Desktop Safari menu bar, go to Safari -> Preferences -> Advances -> Show Desktop menu in menu bar.

    Sometimes the connection between Desktop Safari and Xcode simulator will be broken. Just quit Safari and open it again. Sometimes it takes time to connect these two apps, so just wait for a while.

    Reply

Leave a Comment