2

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

webmagnets
  • 2,266
  • 3
  • 33
  • 60

2 Answers2

5

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."
Denny Hsu
  • 301
  • 2
  • 10
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.

Gundlev
  • 23
  • 5
  • This sounds right if I'm adding my own print function, but how to I redirect the js window.console.log to webkit.messageHandlers.myMessageHandler – Jason Hocker Sep 06 '16 at 13:46