我在swift中使用javascript。我正在使用JavaScriptCore。我创建了一个锯齿状的JS文件&加载它。下面是JS文件的代码。
function setOldCities(appCities) {
var city_array = appCities.split(',');
for (var i = 0; i < city_array.length; i++) {
// Trim the excess whitespace.
city_array[i] = city_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
jQuery('.map-pin').each(function() {
if (($(this).attr('city') == city_array[i])) {
$(this).addClass("active");
try {
webkit.messageHandlers.callFromActivity.postMessage();
} catch(err) {
console.log('The native context does not exist yet');
}
}
});
}
}
我从swift类调用这个函数。函数被调用但它无法识别什么是jQuery。
从swift调用函数的代码。
func callJsFunction()
{
if let functionFullname = self.jsContext.objectForKeyedSubscript("setOldCities") {
// Call the function that composes the fullname.
filter = "City1,City2";
if let fullname = functionFullname.call(withArguments: [filter]) {
print("JS RESULT \(fullname)")
}
}
}
从Code下面我将JS文件加载到swift上下文中。
func initializeJS() {
self.jsContext = JSContext()
// Add an exception handler.
self.jsContext.exceptionHandler = { context, exception in
if let exc = exception {
print("JS Exception:", exc.toString())
}
}
// Specify the path to the jssource.js file.
if let jsSourcePath = Bundle.main.path(forResource: "maps", ofType: "js", inDirectory: "map/js") {
do {
// Load its contents to a String variable.
let jsSourceContents = try String(contentsOfFile: jsSourcePath)
// Add the Javascript code that currently exists in the jsSourceContents to the Javascript Runtime through the jsContext object.
self.jsContext.evaluateScript(jsSourceContents)
}
catch {
print("error is \(error.localizedDescription)")
}
}
let consoleLogObject = unsafeBitCast(self.consoleLog, to: AnyObject.self)
self.jsContext.setObject(consoleLogObject, forKeyedSubscript: "consoleLog" as (NSCopying & NSObjectProtocol))
_ = self.jsContext.evaluateScript("consoleLog")
}
map-pin 类位于单独的html文件中。我在html文件中包含 maps.js