ios-jsbridge 0.1.2

ios-jsbridge 0.1.2

测试已测试
语言语言 Obj-CObjective C
许可证 Apache 2
发布最后发布2014年12月

Draco Yam 维护。



  • Draco Yam

iOS 桥梁,用于通过 UIWebView 在 Objective C 和 Javascript 之间发送消息
目的是允许一些工作流程和模型代码在 Web 应用、Android 和 iOS 之间共享

ios-bridge 目前正在开发过程中

项目的理念受到 PhoneGap 和 LinkedIn 的启发
要了解更多关于该库的研究以及哲学,请访问 http://blog.dracoyam.com/building-hybrid-ios-app-using-javascript-bridge

安装

该库的安装是通过 Cocoapod 完成的
在 Podfile 中添加以下内容

pod 'ios-jsbridge', '0.1.0'

用法 (IOS)

同步

IOS 端

NSString *value = [JS runJs:@"app.testFun('string')"]

JavaScript 端

window.app = {}
app.testFun = function(value) {
  ... // your implementation
  return 'hello world';
}

异步

IOS 端

[JS runAsyncJs:@"app.test_async" param:@"" success:^(NSArray *result){
  ... // your implement
} fail:^(NSError* err) {
  ... // handle error when the bridge hits timeout
}]

JavaScript 端 我实现了一个助手,用于将数据返回到 iOS,您可以将其复制到您的 JavaScript 文件中

/**
 * Make a log to change the window's href
 * @param {Array} Array of string to print
 */
var log = window._log = function(type) {
  var reply = ""
  for (var i = 1; i < arguments.length; i++) {
    var value = arguments[i]
    if (arguments[i] === Object(arguments[i]) && ((typeof arguments) != "string"))
      value = JSON.stringify(value)
    reply += encodeURIComponent(value)
  }

  var iframe = document.createElement('iframe');
  iframe.setAttribute('src', "js://" + type + "/" + reply);
  document.documentElement.appendChild(iframe);
  iframe.parentNode.removeChild(iframe);
  iframe = null;
}

在从 iOS 端触发的事件中,异步应用程序通常会有一个与键组合的参数

window.app = {}
app.test_async = function(key, req) {
  async_function(function(res) {  // custom async function call
    window._log(key, { ... // custom return object / string })  
    // the key is a counter stored on the IOS Side
  })
}

从 JavaScript 调用 iOS

还实现了一个 JSBridgeNotification,用于捕获从 JS 端来的自定义调用
IOS 端

[[NSNotificationCenter defaultCenter] addObserverForName:@"JSBridgeNotification" object:nil queue:nil usingBlock:^(NSNotification *notification) {
  ... // custom handling here
  ... notification.userInfo contains {host: '', component: ''}
}];

别忘了在 dealloc 函数中删除观察器

JavaScript 端

// Same as sync methods, _log is used, but instead of passing in the key which is not available
// a custom text is passed in 
function() {
  window._log('custom', {test: 'test param'})
}

您还可以查看 IOS_JSBridgeTests.m 来了解如何使用它们