Weex Devtools 能够方便调试 Weex 页面,但此功能离不开 Native 的支持。如何让你的 App 也集成 Devtools,在本章将会详细说明 iOS 端如何接入 Weex Devtools。
建议在DEBUG模式下依赖
在工程目录的 podfile 添加如下代码
source https://github.com/CocoaPods/Specs.git, pod 'WXDevtool', '0.15.3', :configurations => ['Debug'],
可以通过更新本地 podspec repo,pod search 来查询最新版本,在 podfile 文件添加依赖。
git clone git@github.com:weexteam/weex-devtool-iOS.git
如下图示:拖动source目录源文件到目标工程中
在相对较大的互联网 App 研发中, framework 静态库被广泛应用,所以推荐使用方法一接入。
参考PlayGround
中的实现
//方法1 pod依赖方式 #import <TBWXDevtool/WXDevtool.h> //方法2 源码依赖方式 #import "WXDevtool.h"
查看 WXDevtool 头文件如下:
@interface WXDevTool : NSObject + (void)setDebug:(BOOL)isDebug; + (BOOL)isDebug; + (void)launchDevToolDebugWithUrl:(NSString *)url; @end
setDebug
:参数为 YES
时,直接开启调试模式,反之关闭,使用场景如下所述
如果你的应用中存在扫码功能或即将集成扫码功能,推荐使用该方式进行集成,Demo 地址见: Playground App
核心代码为获取扫码链接中的_wx_devtool
参数,并将调试工具与调试服务器链接:
[WXDevTool launchDevToolDebugWithUrl:@"ws://{ip}:{port}/debugProxy/native/{channelid}"];
如果你需要直接让你的应用链接上Weex调试工具,你需要通过如下方式进行集成:
weex debug --port 8888 --channelid 1
去指定端口号及调试进程ID.{ip}
,{port}
,{channelid}
为你本地的值。[WXDevTool setDebug:NO]; [WXDevTool launchDevToolDebugWithUrl:@"ws://{ip}:{port}/debugProxy/native/{channelid}"];
如果程序一启动就开启 Weex 调试,需要在 WeexSDK 引擎初始化之前添加代码,同时需要将Debug开关设置为NO
,进入调试界面后再打开JS Debug
开关(服务链接时对于纯weex项目会丢失首屏Weex页面的消息导致白屏)。
为什么需要页面刷新功能?
如下图所示,当点击 debugger 按钮时,js 的运行环境会从手机端(JavaScriptCore)切换到 Chrome(V8),这时需要重新初始化 Weex 环境,重新渲染页面。页面渲染是需要接入方在自己的页面添加。
什么场景下需要添加页面刷新功能?
如何添加刷新
WXDemoViewController.m
例子在 Weex 页面初始化或 viewDidLoad
方法时添加注册通知,举例如下:
[[NSNotificationCenter defaultCenter] addObserver:self selector:notificationRefreshInstance: name:@"RefreshInstance" object:nil];
最后千万记得在 dealloc
方法中取消通知,如下所示
- (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
页面刷新实现,先销毁当前 instance,然后重新创建 instance,举例如下:
- (void)render { CGFloat width = self.view.frame.size.width; [_instance destroyInstance]; _instance = [[WXSDKInstance alloc] init]; _instance.viewController = self; _instance.frame = CGRectMake(self.view.frame.size.width-width, 0, width, _weexHeight); __weak typeof(self) weakSelf = self; _instance.onCreate = ^(UIView *view) { [weakSelf.weexView removeFromSuperview]; weakSelf.weexView = view; [weakSelf.view addSubview:weakSelf.weexView]; UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, weakSelf.weexView); }; _instance.onFailed = ^(NSError *error) { }; _instance.renderFinish = ^(UIView *view) { [weakSelf updateInstanceState:WeexInstanceAppear]; }; _instance.updateFinish = ^(UIView *view) { }; if (!self.url) { return; } NSURL *URL = [self testURL: [self.url absoluteString]]; NSString *randomURL = [NSString stringWithFormat:@"%@?random=%d",URL.absoluteString,arc4random()]; [_instance renderWithURL:[NSURL URLWithString:randomURL] options:@{@"bundleUrl":URL.absoluteString} data:nil]; }
说明:目前版本需要注册的通知名称为固定的 “RefreshInstance”,下个版本会添加用户自定义 name 。
文档见 Weex Debugger 使用文档。