Swift code snippet, load and run javascript

Before developing an ios (or osx) app, i’ve decided to gradually discover the swift language. So i ask myself how to solve a problem, and if i find the solution i will post the code snippet. (sorry for my terrible English).

I want to load a javascript file and run its functions

This is my javascript file:

var hello = function(message) {
  return "Hello " + message;
}

var hola = function(name) {
  return "Hola " + name + " Cómo estás?";
} 

And this is the “Swift solution”:

import JavaScriptCore

// get the home path directory
let homeDir = NSHomeDirectory() 

// load javascript file in String
let jsSource: String! = String.stringWithContentsOfFile(homeDir+"/mylib.js")

// create a javascript context environment and evaluate script
var context = JSContext()
context.evaluateScript(jsSource)

// get reference to hello() function
let helloFunc = context.objectForKeyedSubscript("hello")
// execute hello() function with parameter
let helloValue = helloFunc.callWithArguments(["World!!!"])

// get reference to hola() function
let holaFunc = context.objectForKeyedSubscript("hola")
// execute hola() function with parameter
let holaValue = holaFunc.callWithArguments(["Bobby"])

println(helloValue) // print "Hello World!!!"
println(holaValue)  // print "Hola Bobby Cómo estás?"

“Et voilà!”. It seems easy, but if you’ve never programmed with Objective-C, Cocoa, Foundation, … This can be difficult ;).

We’ll see in the next “code snippet”.

blog comments powered by Disqus

Related posts