2

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'. I know it's about Nodejs runtime. I also tried to use browserify to build web3js ,but it showed some "Cannot find module ''web-core" from xxxx" error.

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"]];

js:

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

I know webView is another way to invoke js functions. It's more strange. I wrote the followings in a html which is invoked by my webView.

function getAddress(prvkey)
{
   var web3 = new Web3();
   return prvkey;
   ...
}

It returns an empty string even if I use try-catch. I totally have no idea how to troubleshoot.

Anyone could help me how to use Web3js from obj-c?

Many thanks.

1

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,

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

0

There is a library for IOS :
web3Js in Swift

You can use this library in Objective-C as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.