iOS 8 JavaScriptCore:你将JavaScript文件放在哪里?

时间:2014-11-09 23:28:33

标签: javascript ios swift javascriptcore

如何将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)

}

1 个答案:

答案 0 :(得分:1)

以下代码适用于我:

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项目中,必要时将文件复制到目的地