Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Created February 6, 2016 15:34
Show Gist options
  • Save carlynorama/3a77b9ab1870d83f1a99 to your computer and use it in GitHub Desktop.
Save carlynorama/3a77b9ab1870d83f1a99 to your computer and use it in GitHub Desktop.
Including Javascript in a Swift File, Simple and Clean.
// Resources used
// https://developer.apple.com/library/prerelease/ios/documentation/JavaScriptCore/Reference/JSContext_Ref/index.html
// http://nshipster.com/javascriptcore/
// http://k33g.github.io/2014/06/10/SWIFT-01.html
// https://developer.apple.com/library/ios/recipes/Playground_Help/Chapters/AddAuxilliaryCodetoaPlayground.html
// http://stackoverflow.com/questions/30737262/swift-2-call-can-throw-but-it-is-not-marked-with-try-and-the-error-is-not-ha
// https://forums.developer.apple.com/thread/13049
let myFileURL = NSBundle.mainBundle().URLForResource("myLib", withExtension: "js")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSUTF8StringEncoding)
print(myText)
// http://stackoverflow.com/questions/26573332/reading-a-short-text-file-to-a-string-in-swift
let fileLocation = NSBundle.mainBundle().pathForResource("filename", ofType: "txt")!
let text : String
do
{
text = try String(contentsOfFile: fileLocation)
}
catch
{
text = ""
}
// or
let content = String.stringWithContentsOfFile(path!, encoding: NSUTF8StringEncoding, error: nil)
// or
var err: NSError?
let content = String.stringWithContentsOfFile(path!, encoding: NSUTF8StringEncoding, error: &err)
// http://stackoverflow.com/questions/26976462/swift-playground-files-are-not-readable
-----
let homeDir = NSHomeDirectory()
let file = homeDir+"/myLib2.js"
let myFileURL = NSBundle.mainBundle().URLForResource("myLib", withExtension: "js")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSUTF8StringEncoding)
print(myText)
//: Embedding JavaScript in Swift
import UIKit
import JavaScriptCore
var str = "Hello, playground"
//from http://nshipster.com/javascriptcore/
let context1 = JSContext()
context1.evaluateScript("var num = 5 + 5")
context1.evaluateScript("var names = ['Grace', 'Ada', 'Margaret']")
context1.evaluateScript("var triple = function(value) { return value * 3 }")
let tripleNum: JSValue = context1.evaluateScript("triple(num)")
// load javascript file in String
// needed update from http://k33g.github.io/2014/06/10/SWIFT-01.html
let fileLocation = NSBundle.mainBundle().pathForResource("myLib", ofType: "js")!
print(fileLocation)
let jsSource : String
do {
jsSource = try String(contentsOfFile: fileLocation)
} catch {
jsSource = "Nope."
}
print(jsSource)
//The below used as written http://k33g.github.io/2014/06/10/SWIFT-01.html
// 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"])
print(helloValue) // print "Hello World!!!"
print(holaValue) // print "Hola Bobby Cómo estás?"
// This file goes in the Resources folder of JavascriptPlaytime (View > Navigators > Show Project Navigator)
// This file is straight from the example found at http://k33g.github.io/2014/06/10/SWIFT-01.html
var hello = function(message) {
return "Hello " + message;
}
var hola = function(name) {
return "Hola " + name + " Cómo estás?";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment