CocoaHeadsSKG
Dimitri James Tsiflitzis
The JavaScriptCore Framework provides the ability to evaluate JavaScript programs from within Swift, Objective-C, C-based apps & vice versa. And inter operably.
Documentation - https://developer.apple.com/documentation/javascriptcore
A JSContext object represents a JavaScript execution environment. You create and use JavaScript contexts to evaluate JavaScript scripts from Objective-C or Swift code, to access values defined in or calculated in JavaScript, and to make native objects, methods, or functions accessible to JavaScript.
We are using JSContext’s evaluateScript: method to define our JavaScript function. This method takes a string representation of some JavaScript code. Either include this string in a variable or load you JS from a file in your app's bundle.
A JSValue instance is a reference to a JavaScript value. You use the JSValue class to convert basic values (such as numbers and strings) between JavaScript and Objective-C or Swift representations in order to pass data between native code and JavaScript code.
Now whenever a JavaScript exception occurs, the exception message (the value parameter passed into the block) will be logged. The exception will give us some helpful information about what went wrong in the JavaScript code.
context?.exceptionHandler = { context, exception in
if let e = exception
{
print("JS Exception:", e.toString())
}
}func deviceInfo()
{
let color = "red"
let javaScriptString = "changeColor(\(color));"
webView.evaluateJavaScript(javaScriptString, completionHandler: nil)
}
changeColor(color) {
var x = document.getElementById("demo"); // Get the element with id="demo"
x.style.color = color; // Change the color of the element
}let handler: @convention(block) ([Int]) -> Void = { numbers in
}
let something: @convention(block) (String, [String: String]) -> Void = { stringValue, dictionary in
}CocoaHeadsSKG
Dimitri James Tsiflitzis