Kimi Wu Kimi Wu - 1 year ago 61
Objective-C Question

Ojbc invoke js error: Can't find variable require

I'm totally new to JS. I'm developing on ios and we need to use Web3js in our program. It's ok to call js function in obj-c. However, I use 'require' to import Web3js modules, it throws 'ReferenceError: Can't find variable: require'. What happens? Did I miss anything?
Anyone can help?? Many thanks.


If 'require' is not usable, how could I use other modules from js invoked by obj-c?

here is my code.

obj-c code:

NSString* path = [[NSBundle mainBundle] pathForResource:@"bridge/src/index" ofType:@"js"];
jsFunc = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

JSContext* jsContext = [[JSContext alloc] init];
[jsContext evaluateScript:jsFunc];
JSValue* func = jsContext[@"getAddress"];
JSValue* = [func2 callWithArguments:@[@"0x8730f6ad1c0d387644590966bdbfedba44fe250118df0f97f11190ad5727b312"]];


function getAddress(prvKey)
var Web3 = require('../../3rd_party/web3.js-1.0.0');
var web3 = new Web3();
return web3.eth.accounts.privateKeyToAccount(prvKey);
catch (e)
return e;

Answer Source

I used Browserify to package all modules and then used webView to call the js functions.

here is my js file, index.js

"use strict"
let Web3 = require('web3.js');
window.Web3 = Web3;

and then use Broswerify to pack

browserify index.js -o web3.js

my html,

    <script type="text/javascript" src="web3.js"></script>   
    <script type="text/javascript">
        function getAddress(prvkey)
                var web3 = new Web3();
                var account  = web3.eth.accounts.privateKeyToAccount(prvkey);
                return account.address;
            catch (e)
                return e;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download