Weex 项目生成###
Weex是阿里研发的一个框架,解决iOS原生WebView不灵活的特点。今天就讲讲Weex集成到iOS项目中。
首先得确保安装了Weex框架。
$ npm install -g weex-toolkit@beta
cd 到项目的文件夹下,创建项目
$ weex init projectName
cd到项目下,为项目导入依赖
$ npm install
开启服务
$ npm run dev
开启观察者(方便实时调试)
$ npm run serve
Weex集成至iOS项目###
修改CoCoapods
target 'WeexIOS' do
pod 'WeexSDK','~> 0.9.5'
end
cocoapods Update好之后,可以设置环境
在AppDegelate里设置
#import "AppDelegate.h"
#import "ViewController.h"
#import <WeexSDK/WXSDKEngine.h>
#import <WeexSDK/WXAppConfiguration.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//business configuration
[WXAppConfiguration setAppGroup:@"AliApp"];
[WXAppConfiguration setAppName:@"WeexDemo"];
[WXAppConfiguration setAppVersion:@"1.0.0"];
//init sdk enviroment
[WXSDKEngine initSDKEnviroment];
ViewController *vc=[[ViewController alloc] init];
self.window.rootViewController=vc;
return YES;
}
然后初始化ViewController,将生成的js文件导入项目中
#import "ViewController.h"
#import <WeexSDK/WXSDKInstance.h>
@interface ViewController ()
@property (nonatomic, strong) WXSDKInstance *instance;
@property (nonatomic, strong) UIView *weexView;
@end
@implementation ViewController{
NSURL *jsUrl;
}
- (void)viewDidLoad {
[super viewDidLoad];
_instance = [[WXSDKInstance alloc] init];
_instance.viewController = self;
_instance.frame=self.view.frame;
__weak typeof(self) weakSelf = self;
NSString *path=[NSString stringWithFormat:@"file://%@/JS/app.weex.js",[NSBundle mainBundle].bundlePath];
NSLog(@"-----path:%@",path);
jsUrl=[NSURL URLWithString:path];
if (!jsUrl) {
return;
}
[_instance renderWithURL: jsUrl];
_instance.onCreate = ^(UIView *view) {
[weakSelf.weexView removeFromSuperview];
weakSelf.weexView = view;
[weakSelf.view addSubview:weakSelf.weexView];
};
_instance.onFailed = ^(NSError *error) {
NSLog(@"加载错误");
};
_instance.renderFinish = ^ (UIView *view) {
NSLog(@"加载完成");
};
}
- (void)dealloc
{
[_instance destroyInstance];
}
这里需要注意的是renderWithURL这个方法最好还是写在前面,官方的文档里把这个方法写在最后,可是运行起来界面没有任何反应,而且控制台报出“no data return”。可是将renderWithURL这个方法提到前面一切都好了。
结语###
给个彩蛋,其实还有更简单的方式部署到iOS项目,直接用Weepack就可以。详细请参看https://github.com/weexteam/weex-pack