'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?



Solution 1:[1]

You can use desktop Safari developer tool.

  1. Run Xcode Simulator.
  2. Open desktop Safari developer tool. Safari menu -> Develop -> Simulator-iPhone XXX -> your Xcode Simulator app name. Then a Web Inspector shows up. To show "Develop" item in Safari menu bar, go to Safari menu -> Preferences -> Advances -> Show Desktop menu in menu bar.
  3. All console.log() messages will be printed on the Web Inspector "Console" tab when you run the Xcode Simulator. Choose the right filter in the Web Inspector such as "All" or "Logs."

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gundlev