Created
May 27, 2019 16:01
-
-
Save BrunoMiguens/5b6111623be66c2e265f4ec8955f6bea to your computer and use it in GitHub Desktop.
[Medium] Swift: Using Javascript library - Swift Playground File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import JavaScriptCore | |
import PlaygroundSupport | |
func generateContextJS() -> JSContext? { | |
let context = JSContext() | |
context?.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }") | |
let consoleLog: (String) -> Void = { message in | |
print("JS Log: \(message)") | |
} | |
context?.setObject(consoleLog, forKeyedSubscript: "_consoleLog" as NSCopying & NSObjectProtocol) | |
context?.exceptionHandler = { context, exception in | |
print("JS Error: \(exception.debugDescription)") | |
} | |
return context | |
} | |
func loadJSBundle(for context: JSContext?) { | |
guard let libraryPath = Bundle.main.path(forResource: "cson-parser-bundle", ofType: "js"), | |
let libraryCode = try? String(contentsOfFile: libraryPath) else { | |
return | |
} | |
context?.evaluateScript(libraryCode) | |
} | |
let context = generateContextJS() | |
loadJSBundle(for: context) | |
if let csonPath = Bundle.main.path(forResource: "cson-sample", ofType: "cson"), let csonData = try? String(contentsOfFile: csonPath) { | |
context?.setObject(csonData, forKeyedSubscript: "parseStringData" as NSCopying & NSObjectProtocol) | |
let jsonData = context?.evaluateScript("CSON.parse(parseStringData)")?.toDictionary() | |
print(jsonData?.description ?? "") | |
} | |
PlaygroundPage.current.needsIndefiniteExecution = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment