iOS 8 JavaScriptCore: Where do you place your JavaScript files at?

怎甘沉沦 提交于 2021-02-08 09:24:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!