Cannot use Swift class from JavaScriptCore

I want to instantiate a Swift class in the context of a JavaScriptCore.

I tried different syntaxes with the playground, and also tried to use Xcode 6.4 (Swift 1.2) and Xcode 7 beta 3 (Swift 2.0), but without success = - (

Maybe something is missing for me.

In a more complex example that I found on the network, the protocol's “create” function was defined as a “func class”, but the compiler rejects this syntax, saying: “Class methods are allowed only in classes, use“ static ”to declare a static method" ... so what I did.

Here is my code (OS X 10.10.4 - Xcode 6.4). I am using Playground:

//: Playground - noun: a place where people can play

import Foundation
import JavaScriptCore

let context = JSContext()

// errors handling
context.exceptionHandler = { context, exception in
    println("JS Error: \(exception)")
}

@objc
protocol PersonJavaScritMethod : JSExport {
    func sayHello()
    static func create(name : String) -> Person
}

class Person : NSObject, PersonJavaScritMethod {
    var name : String!

    init(name:String) {
        super.init()
        println("# init done #")
        self.name = name
    }

    class func create(name : String) -> Person {
        return Person(name: name)
    }

    func sayHello() {
        println("Hello \(name)")
    }
}

let aPerson = Person.create("Toto")
// -> ok : console output : "# init done #"
aPerson.sayHello()
// -> ok : console output : "Hello Toto"

context.globalObject.setObject(Person.self, forKeyedSubscript: "Person")
context.evaluateScript("Person.create('Mike')")
// -> not ok : console output :
// "JS Error: TypeError: undefined is not a function (evaluating 'Person.create('Mike')')"
+4
source share
1

XCode 8.2.1 swift3 ( , / Swift 3):

context.evaluateScript("Person.createWithName('Mike')")
0

Source: https://habr.com/ru/post/1599562/


All Articles