swift 与 web3.js 交互

部署合约

1.用Solidity语言编写合约内容
pragma solidity ^0.4.4;

contract Car {
  // Vehicle identifier, can be VIN-number, etc.
  bytes public vehicleName = "Tesla";
  // We’ll use public so no need to have getOwner method
  bytes16 public owner;

  function Car() {
    // constructor
  }

  function setOwner(bytes16 newOwner)
  {
    owner = newOwner;
  }
}

2.对合约类进行编译,获得abiDefinition和bytecode

因为geth 1.6已经取消了eth.complie,所以合约的编译不能在geth中完成。只能通过solc或者在线工具https://ethereum.github.io/browser-solidity 完成。因为solc只能在linux下编译,实验环境是windows,选择在线工具。
用浏览器打开在线工具,并将步骤一的合约粘贴入工具左侧的文本区中
因为当前自动编译选项为勾选状态,所以工具会对合约进行自动编译。这时,我们需要点击“Details”按钮

3.通过abiDefinition和bytecode实例化合约并进行布署

// 以下两段即是步骤二获取的abiDefinition和bytecode数据
abi=[ { "constant": true, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "bytes16" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "vehicleName", "outputs": [ { "name": "", "type": "bytes" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "newOwner", "type": "bytes16" } ], "name": "setOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } ]

bytecode="0x60606040526040805190810160405280600581526020017f5465736c610000000000000000000000000000000000000000000000000000008152506000908051906020019061004f929190610060565b50341561005b57600080fd5b610105565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100a157805160ff19168380011785556100cf565b828001600101855582156100cf579182015b828111156100ce5782518255916020019190600101906100b3565b5b5090506100dc91906100e0565b5090565b61010291905b808211156100fe5760008160009055506001016100e6565b5090565b90565b61029a806101146000396000f300606060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638da5cb5b1461005c578063d602f858146100ab578063d9a4dfa614610139575b600080fd5b341561006757600080fd5b61006f61016f565b60405180826fffffffffffffffffffffffffffffffff19166fffffffffffffffffffffffffffffffff1916815260200191505060405180910390f35b34156100b657600080fd5b6100be610192565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100fe5780820151818401526020810190506100e3565b50505050905090810190601f16801561012b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014457600080fd5b61016d60048080356fffffffffffffffffffffffffffffffff1916906020019091905050610230565b005b600160009054906101000a90047001000000000000000000000000000000000281565b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156102285780601f106101fd57610100808354040283529160200191610228565b820191906000526020600020905b81548152906001019060200180831161020b57829003601f168201915b505050505081565b80600160006101000a8154816fffffffffffffffffffffffffffffffff021916908370010000000000000000000000000000000090040217905550505600a165627a7a723058202ba2be8d3625b2ec2dd1fb9c379e2a107063b2b356f6ab744ba5581aae3a03c40029"
// 创建合约
var contract = eth.contract(abi);
var initializer = {from: web3.eth.accounts[0], data: bytecode, gas: 300000};
// 在合约调用之前,需要对用户进行解锁
personal.unlockAccount(eth.accounts[0],"123456")
var token = contract.new(initializer)
// 合约创建完成之后,打印token.address为空
// 需要通过挖矿这一步骤,对合约地址进行确认
miner.start(4);
admin.sleepBlocks(2);
miner.stop();

swift代码

func loadHtml() {
    if let path = Bundle.main.path(forResource: "web3", ofType: "html") {
      let url = URL(fileURLWithPath: path)
      let request = URLRequest(url: url)
      
      webView?.load(request)
      webView?.navigationDelegate = self
    }
  }

WKNavigationDelegate代理方法
判断web3是否连接

extension ViewController: WKNavigationDelegate {
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webViewIsConnect()
  }
  func webViewIsConnect() {
    self.webView?.evaluateJavaScript("web3.isConnected()",
                                     completionHandler: {(res, error) in
                                      if let connected = res, connected as! NSInteger == 1
                                      {
                                        self.isConnectedLabel.text = "Connected"
                                        print("Connected")
                                      }
                                      else
                                      {
                                        self.isConnectedLabel.text = "Disabled"
                                        print("Disabled")
                                      }
    })
  }
}

调用本地html js代码

@IBAction func getOwner(_ sender: Any) {
    webView!.evaluateJavaScript("getNameAndOwner()",
                                completionHandler: {(res, error) in
                                  if let carData = res as? NSDictionary
                                  {
                                    self.owner.text = "The owner of the \"\(carData["name"]!)\" car is \"\(carData["owner"]!)\""
                                  }
    }
    )
  }

js代码

    var web3 = new Web3();
    web3.setProvider(new web3.providers.HttpProvider("http://192.168.192.169:8200"));
    console.log(web3.isConnected())

    var abi =[  { "constant": true, "inputs": [], "name": "owner", "outputs": [     { "name": "", "type": "bytes16"     } ], "payable": false, "stateMutability": "view", "type": "function"    },  { "constant": true, "inputs": [], "name": "vehicleName", "outputs": [   { "name": "",   "type": "bytes"     } ], "payable": false, "stateMutability": "view", "type": "function"    },  { "constant": false, "inputs": [ { "name": "newOwner", "type": "bytes16"    } ], "name": "setOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"   },  { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor"    } ];
    var contractAddress = "0xff657546deda792a482c586ca16b76d6144926e1"
    var Car = web3.eth.contract(abi).at(contractAddress);
    function getNameAndOwner() {
      // Get hex values from the contract and convert them into ascii string
      console.log("------------");
      console.log(Car)
      let name = Car.vehicleName().toString();
      let owner = Car.owner().toString();
      console.log("name"+name);
      console.log("owner"+owner);
      return {
        name: web3.toAscii(name),
        owner: web3.toAscii(owner)
      };
    }

参考链接
How to run Web3.js in Swift 2 / iOS to work with Ethereum
以太坊私链与智能合约部署学习

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,142评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,298评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,068评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,081评论 1 291
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,099评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,071评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,990评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,832评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,274评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,488评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,649评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,378评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,979评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,625评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,643评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,545评论 2 352

推荐阅读更多精彩内容