Swift
Swift
Call a JavaScript Function Returning an Object
See more JavaScript Examples
Demonstrates how to call a JavaScript function that returns an object.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This is the JavaScript function we'll call:
// function getSettings() {
// return {
// theme: "dark",
// notifications: true,
// version: 1.0
// };
// }
let sbScript = CkoStringBuilder()!
sbScript.append(value: "function getSettings() {")
sbScript.append(value: " return {")
sbScript.append(value: " theme: \"dark\",")
sbScript.append(value: " notifications: true,")
sbScript.append(value: " version: 1.0")
sbScript.append(value: " };")
sbScript.append(value: "}")
let js = CkoJs()!
let result = CkoJsonObject()!
result.emitCompact = false
// Call Eval to add the function to the context's global object
success = js.eval(jscript: sbScript, result: result)
if success == false {
// Examine the result for an exception.
print("\(result.emit()!)")
// Also examine the LastErrorText.
print("\(js.lastErrorText!)")
return
}
// ------------------------------------------------------------------------------
// Call the function getSettings()
let funcCall = CkoJsonObject()!
// Create JSON specifying the function name and arguments
// The function has no arguments, so we only specify the name.
// {
// "name": "getSettings",
// }
funcCall.updateString(jsonPath: "name", value: "getSettings")
success = js.callFunction(func: funcCall, result: result)
if success == false {
// Examine the result for an exception.
print("\(result.emit()!)")
// Also examine the LastErrorText.
print("\(js.lastErrorText!)")
return
}
print("\(result.emit()!)")
// Output:
// {
// "type": "object",
// "value": {
// "theme": "dark",
// "notifications": true,
// "version": 1
// }
// }
// Examine the object's members
print("theme: \(result.string(of: "value.theme")!)")
print("notifications: \(result.bool(of: "value.notifications"))")
print("version: \(result.int(of: "value.version").intValue)")
// Output:
// theme: dark
// notifications: True
// version: 1
}