问题
How do you add a JS file to the home directory so that 's' does not return 'nil'. Thanks.
func analyzeText(text: String) {
let homeDir = NSHomeDirectory()
var err: NSError? = NSError()
let s = String(contentsOfFile: homeDir + "/text.js", encoding: NSUTF8StringEncoding, error: &err)
println(s)
var context = JSContext(virtualMachine: JSVirtualMachine())
context.evaluateScript(s)
let analyzeText = context.objectForKeyedSubscript("analyzeText")
let analyzeTextVal = analyzeText.callWithArguments([text])
println(analyzeTextVal)
}
回答1:
The following code works for me:
func analyzeText(scriptName: String) {
var ext = scriptName.pathExtension
var fileName = scriptName.substringToIndex(
advance(scriptName.startIndex,
scriptName.utf16Count - ext.utf16Count - 1))
if fileExtension.utf16Count == 0 {
fileName = scriptName
ext = "js"
}
let url = NSBundle.mainBundle()
.URLForResource(fileName, withExtension: ext)
let scriptCode = String(contentsOfURL: url!,
encoding: NSUTF8StringEncoding,
error: nil)!
var context = JSContext(virtualMachine: JSVirtualMachine())
context.evaluateScript(scriptCode)
/* ... */
}
To evaluate a file called text.js
, do the following:
analyzeText("text")
Be sure to have added text.js
to the Xcode project copying the file if necessary to the destination
来源:https://stackoverflow.com/questions/26834563/ios-8-javascriptcore-where-do-you-place-your-javascript-files-at