本文介绍在iOS中使用Doric的方式及常用API
项目引入
在pod spec中添加:
// 请注意sdkVersion需>=当前项目中的doric js库版本
pod 'DoricCore', '~>${sdkVersion}'安装pod
$ pod install
初始化与注册
如果业务有自定义插件或视图,需要在加载 Doric 页面前注册:
[Doric registerLibrary:[MyLibrary new]]; |
可选配置:
[Doric enablePerformance:YES]; |
常用参数说明
本小节内容解释Doric SDK参数名词及意义。
source
标示JS bundle的来源,DoricJSLoader可根据source请求到JS bundle内容。
alias
用于标识Doric运行时,用于热重载调试。可为空。
extra
初始化DoricJS时传入的额外数据,在Panel中,可通过getInitData获取。为JSON格式的字符串。可传空。
示例:
NSString *extra = @"{\"userId\":\"10001\"}"; |
JS 侧读取:
const initData = this.getInitData(); |
Doric容器
Doric容器可以接收Doric JS bundle并运行。
DoricViewController
经DoricViewController装载的Doric程序可绘制在整个ViewController之上。
DoricViewController *doricViewController = [[DoricViewController alloc] initWithSource:[NSString stringWithFormat:@"assets://src/%@.js", bundleName] |
DoricPanel
更细粒度的Doric容器,需直接传入JS bundle内容。jsBundleString可通过DoricJSLoader获取。
DoricPanel *panel = [DoricPanel new]; |
Bundle装载 - DoricJSLoader
DoricJSLoader的作用是根据Source协议请求加载JS内容。
Doric内部实现了通过assets文件或http/https地址加载。
您也可以按如下注册自己的DoricJSLoader来实现自定义协议。
使用
Doric内置了两种协议实现
- App内文件,source格式为
assets://xxxxxx。xxxxxx即为文件相对MainBundle的路径。 - Http或Https协议,source格式即为http地址,
https://example.com/bundle.js
NSString *source = @"assets://src/HelloDoric.js"; |
注册
您可以注册DoricJSLoader来实现对JS Bundle的自定义请求下载。
@protocol DoricLoaderProtocol <NSObject> |
实现接口
@interface DoricHttpJSLoader : NSObject <DoricLoaderProtocol> |
注册生效
创建JSLoader的实例并在Doric中注册
[Doric addJSLoader:[DoricHttpJSLoader new]]; |
运行脚手架 iOS 工程
通过 doric create 创建的项目可以直接运行:
$ npm run ios |
该命令会执行:
- 使用
xcrun xctrace list devices列出设备与模拟器。 - 选择目标设备。
- 在
iOS/下执行pod install。 - 使用
xcodebuild构建。 - 模拟器使用
xcrun simctl install/launch。 - 真机使用
ios-deploy安装并启动。
运行前请确认:
- 已安装 Xcode 与 CocoaPods。
- 真机运行时已安装或允许安装
ios-deploy。 - 当前目录是 Doric 应用根目录。