gpt4 book ai didi

javascript - iOS 8 JavaScript 核心 : Where do you place your JavaScript files at?

转载 作者:行者123 更新时间:2023-11-28 07:14:38 25 4
gpt4 key购买 nike

如何将 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.js 添加到 Xcode 项目中,必要时将文件复制到目标位置

关于javascript - iOS 8 JavaScript 核心 : Where do you place your JavaScript files at?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26834563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com