集成 Weex 到 iOS

使用 CocoaPods集成到iOS应用 - 图1Carthage集成到iOS应用 - 图2 可以方便地将 Weex 集成到自己的项目中。

1. 配置依赖

使用 CocoaPods

从 Cocoapods 仓库集成到iOS应用 - 图3中获取 WeexSDK 的最新版本。

将 WeexSDK 添加到你的 Podfile 中。

  1. source 'git@github.com:CocoaPods/Specs.git'
  2. target 'YourTarget' do
  3. platform :ios, '8.0'
  4. pod 'WeexSDK', '0.20.1'
  5. end

运行 pod install 命令安装依赖。

使用 Carthage

在工程中创建一个 Cartfile,Carthage 使用方法集成到iOS应用 - 图4

添加 github "apache/incubator-weex"Cartfile集成到iOS应用 - 图5

运行 carthage update

2. 初始化 Weex

建议在 didFinishLaunchingWithOptions 回调中初始化 Weex,你也可以在子线程中异步初始化,但需要确保渲染 Weex 页面前初始化已经全部完成。

  1. // App configuration
  2. [WXAppConfiguration setAppGroup:@"Your app group"];
  3. [WXAppConfiguration setAppName:@"Your app name"];
  4. [WXAppConfiguration setAppVersion:@"Your app version"];
  5. //Initialize WeexSDK
  6. [WXSDKEngine initSDKEnvironment];
  7. //Register custom modules and components, optional.
  8. [WXSDKEngine registerComponent:@"myview" withClass:[MyViewComponent class]];
  9. [WXSDKEngine registerModule:@"mymodule" withClass:[MyWeexModule class]];
  10. //Register the implementation of protocol, optional.
  11. [WXSDKEngine registerHandler:[WXAppNavigationImpl new] withProtocol:@protocol(WXNavigationProtocol)];
  12. //Set the log level, optional
  13. [WXLog setLogLevel: WXLogLevelWarning];

3. 创建一个 Weex 实例

你既可以在全页面中使用 Weex,也可以在一个 view 中渲染 Weex。只需要创建一个 Weex 实例并指定好回调方法,提供一个合法的 URL 就可以了。在 onCreate 回调方法中将根 view 添加到你想显示内容的地方,并通过 instance.frame = 来设置它的尺寸和位置。

  1. #import <WeexSDK/WXSDKInstance.h>
  2. - (void)viewDidLoad
  3. {
  4. [super viewDidLoad];
  5. _instance = [[WXSDKInstance alloc] init];
  6. _instance.viewController = self;
  7. _instance.frame = self.view.frame;
  8. __weak typeof(self) weakSelf = self;
  9. _instance.onCreate = ^(UIView *view) {
  10. [weakSelf.weexView removeFromSuperview];
  11. weakSelf.weexView = view;
  12. [weakSelf.view addSubview:view];
  13. };
  14. _instance.onFailed = ^(NSError *error) {
  15. //process failure, you could open an h5 web page instead or just show the error.
  16. };
  17. _instance.renderFinish = ^ (UIView *view) {
  18. //process renderFinish
  19. };
  20. NSURL *url = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"js"];
  21. [_instance renderWithURL:url options:@{@"bundleUrl":[self.url absoluteString]} data:nil];
  22. }

4. 销毁实例

必须显式地销毁 Weex 实例,否则可能引起内存泄漏。

  1. [instance destroyInstance];

5. 扩展 Weex

Weex 支持自定义组件、模块,可以参考以下两篇文档。

6. 在 iPad 中使用 Weex

当页面渲染完成后,屏幕再旋转,页面不会自动适配。所以,如果你的 App 允许屏幕旋转,务必在页面渲染前更新屏幕宽度。

前端样式中指定的坐标在渲染时会根据 屏幕宽度当前页面的 view-port-width 进行换算。

修改 view-port-width 的方法,会影响前端代码,通常不要设置,默认为 750px。

  1. beforeCreate(){
  2. const meta = weex.requireModule('meta');
  3. meta.setViewport({
  4. width: 1536
  5. });
  6. }

监听 UIDeviceOrientationDidChangeNotification 通知,并调用下面方法修改屏幕尺寸(假设已经旋转完成,[UIScreen mainScreen].bounds.size.width 就是当前宽度)

  1. [WXCoreBridge setDeviceSize:[UIScreen mainScreen].bounds.size];