如何将JS文件添加到主目录,以使“s”不返回“nil”。谢谢。
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)
}
最佳答案
以下代码对我有用:
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)
/* ... */
}
要评估名为
text.js
的文件,请执行以下操作:analyzeText("text")
确保已将
text.js
添加到Xcode项目中,如果需要将文件复制到目标位置