I have this code and node_modules in shared folder in x code project. It have to show me text key generated from js-code. js-code works outside by node.js, but it shows me 'undefined' in Content View. Can I import js modules in x code project? Will it work on iPhone?
// ContentView.swift
// Shared
import Foundation
import SwiftUI
import JavaScriptCore
class Cube {
func doJS(text: String) -> String? {
let jsSource = "var testFunct = function test(message) { const NodeRSA = require('node-rsa'); const key = new NodeRSA(); var k = key.generateKeyPair(); var p = k.exportKey('pkcs1'); return p};"
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("testFunct")
return testFunction?.call(withArguments: [text]).toString()
}
}
struct ContentView: View {
var body: some View {
Text(Cube().doJS(text: "Hello, world!") ?? "No result")
.fontWeight(.black)
.foregroundColor(Color.green)
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
My js code:
// npm install node-rsa
// https://www.npmjs.com/package/node-rsa
var testFunct = function test(message) {
const NodeRSA = require('node-rsa');
const key = new NodeRSA();
var k = key.generateKeyPair();
var p = k.exportKey('pkcs1');
return p};
console.log(testFunct())