简体   繁体   中英

Swift JSContext always returns nil

I am trying to integrate EOS JavaScript library into my iOS application. I have installed an npm module and by using browserify i created a single bundle file. The code for that looks like this:

'use strict';
var ecc = require('eosjs-ecc')

module.exports = ecc;

Then I ran the command: browserify index.js --standalone ecc > bundle.js

Integrating this into a simple HTML file works, so if I do a test with the example they provide on Github like so:

<html>
 <head>
   <meta charset="utf-8">
   <script src="bundle.js"></script>
 </head>
<body>
<script type="text/javascript">
    let gg = ecc.randomKey().then(privateKey => {
        console.log('Private Key:\t', privateKey) // wif
        console.log('Public Key:\t', ecc.privateToPublic(privateKey)) // EOSkey...
        })
</script>

I get an output to the console. However, integrating this back to the iOS application does not work.

Here's my code:

import JavaScriptCore

class EOSJSService {

  var jsContext: JSContext!

  init() {
    self.jsContext = JSContext()

    if let jsSourcePath = Bundle.main.path(forResource: "bundle", ofType: "js") {
        do {
            let jsSourceContents = try String(contentsOfFile: jsSourcePath)

            self.jsContext.evaluateScript(jsSourceContents)
            initEOS()
        }
        catch {
            print(error.localizedDescription)
        }
    } else {

    }
  }

  private func initEOS() {
     let test = jsContext.evaluateScript("ecc")

  }
}

Whatever I put in jsContext.evaluateScript it's always returning undefined. I've tried bundling it into a class, putting a dummy hello world variable inside it's always returning undefined.

When you import bundle.js from html, the js itself may refer to other js file given that you are installing the whole thing through npm, instead of some static file that you can just download and use. This is why it works in html, that the js file can find it's references. On swift side, it may not.

Generally, swift is not good at working with javascript file. Also, it will be hard for you to maintain two piece of code. If you are trying to do some encryting, try some native swift & Objective-c library like CryptoSwift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM