iOS weex使用

1 篇文章 0 订阅
1 篇文章 0 订阅

阿里 Weex,一个UI跨平台的框架,使用vue编写,编译为.js文件,供移动端进行调用
iOS 端使用 pod ‘WeexSDK’ 引入sdk

一.weex使用,直接上代码吧

1.appdelete中执行的代码,其中WXEventModule是交互相关,WXImgLoaderDefaultImpl是加载图片用到的

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     //weex
    [WXAppConfiguration setAppGroup:@"wang"];
    [WXAppConfiguration setAppName:@"xixi"];
    [WXAppConfiguration setAppVersion:@"1.0"];
    //init sdk environment
    [WXSDKEngine initSDKEnvironment];
    //register custom module and component,optional
    [WXSDKEngine registerModule:@"globalEvent" withClass:NSClassFromString(@"WXEventModule")];
    [WXSDKEngine registerHandler:[WXImgLoaderDefaultImpl new] withProtocol:@protocol(WXImgLoaderProtocol)];
    //set the log level
    [WXLog setLogLevel: WXLogLevelAll];
    [YaoTiaoLocationModel shareInstance];
}

2.先看WXEventModule,它的主要作用是把js文件中的点击方法传入oc中,执行原生的代码。下面看具体的类文件
先看.h文件,没什么东西

#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface WXEventModule : NSObject
@end
NS_ASSUME_NONNULL_END

再看.m文件,WX_EXPORT_METHOD是使用方法名注册,然后再实现方法体

#import "WXEventModule.h"
#import <WeexSDK/WeexSDK.h>
@interface WXEventModule ()<WXModuleProtocol>
@end
@implementation WXEventModule
@synthesize weexInstance;
WX_EXPORT_METHOD(@selector(tosearch:))//搜索框
- (void)push:(NSString *)url
{
   //在这执行想要的代码
}

3.WXImgLoaderDefaultImpl这个类是利用sdwebimage框架加载图片展示.h文件

#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface WXImgLoaderDefaultImpl : NSObject<WXImgLoaderProtocol, WXModuleProtocol>
@end
NS_ASSUME_NONNULL_END
.m文件实现,需要导入sdwebimage相关头文件,我是在pch文件里引入的
#import "WXImgLoaderDefaultImpl.h"
@implementation WXImgLoaderDefaultImpl
- (id<WXImageOperationProtocol>)downloadImageWithURL:(NSString *)url imageFrame:(CGRect)imageFrame userInfo:(NSDictionary *)userInfo completed:(void(^)(UIImage *image,  NSError *error, BOOL finished))completedBlock
{
    if (![self isValidString:url])
    {
        return nil;
    }
    //实现加载xcassets 本地资源文件
    if ([url hasPrefix:@"assets:"])
    {
        UIImage *image = [UIImage imageNamed:[url substringFromIndex:7]];
        completedBlock(image, nil, YES);
        return (id<WXImageOperationProtocol>)[NSObject new];
    }
    
    if ([url hasPrefix:@"//"])
    {
        url = [@"http:" stringByAppendingString:url];
    }
    
    return (id<WXImageOperationProtocol>)[[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:url] options:SDWebImageRefreshCached progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL)
            {
                
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL)
            {
                if (completedBlock)
                {
                    if (!image)
                    {
                        //当图片记载失败的时候,回调本地的占位图展示,同时,回调的error要置空,这是项目要求的,也可以选择不加载,尤其是imageVew尺寸不一的情况下
                        completedBlock([UIImage imageNamed:@"goodTakePlace"],nil, finished);
                    }
                    else
                    {
                        completedBlock(image, error, finished);
                    }
                }
            }];
}
- (BOOL)isValidString:(NSString *)str
{
    if (str && [str isKindOfClass:[NSString class]] && [str length] > 0)
    {
        return YES;
    }
    return NO;
}

4.看页面如何加载weex

#import "HomeViewController.h"
#import <WeexSDK/WXSDKInstance.h>
@interface HomeViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKDistrictSearchDelegate,BMKGeoCodeSearchDelegate>
@property (nonatomic, strong) WXSDKInstance *instance;
@property (nonatomic, strong) UIView *weexView;
@property (nonatomic, strong) NSURL *sourceURL;
@property (nonatomic,strong) NoDataAndErrorView * noDataView;
@end
@implementation HomeViewController
- (void)dealloc
{
    [_instance destroyInstance];
    [self _removeObservers];
}
- (instancetype)initWithSourceURL:(NSURL *)sourceURL
{
    if ((self = [super init]))
    {
        self.sourceURL = sourceURL;
        [self _addObservers];
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    if ([self.navigationController isKindOfClass:[WXRootViewController class]])
    {
        CGRect frame = self.view.frame;
        frame.origin.y = 0;
        frame.size.height = [UIScreen mainScreen].bounds.size.height;
        self.view.frame = frame;
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self _renderWithURL:_sourceURL];
    if ([self.navigationController isKindOfClass:[WXRootViewController class]]) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
    self.title = @"首页";
    self.view.backgroundColor = [UIColor whiteColor];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self _updateInstanceState:WeexInstanceAppear];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self _updateInstanceState:WeexInstanceDisappear];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    [self _updateInstanceState:WeexInstanceMemoryWarning];
}
- (void)refreshWeex
{
    [self _renderWithURL:_sourceURL];
}
- (void)addEdgePop
{
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
- (void)_renderWithURL:(NSURL *)sourceURL
{
    if (!sourceURL)
    {
        return;
    }
    
    [_instance destroyInstance];
    if ([WXPrerenderManager isTaskReady:[self.sourceURL absoluteString]])
    {
        _instance = [WXPrerenderManager instanceFromUrl:self.sourceURL.absoluteString];
    }
    _instance = [[WXSDKInstance alloc] init];
    [_instance setFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - [UIApplication sharedApplication].statusBarFrame.size.height - self.navigationController.navigationBar.frame.size.height - self.tabBarController.tabBar.frame.size.height)];
    _instance.pageObject = self;
    _instance.pageName = sourceURL.absoluteString;
    _instance.viewController = self;
    
    NSString *newURL = nil;
    
    if ([sourceURL.absoluteString rangeOfString:@"?"].location != NSNotFound)
    {
        newURL = [NSString stringWithFormat:@"%@&random=%d", sourceURL.absoluteString, arc4random()];
    }
    else
    {
        newURL = [NSString stringWithFormat:@"%@?random=%d", sourceURL.absoluteString, arc4random()];
    }
    [_instance renderWithURL:[NSURL URLWithString:newURL] options:@{@"bundleUrl":sourceURL.absoluteString} data:nil];
    
    __weak typeof(self) weakSelf = self;
    _instance.onCreate = ^(UIView *view)
    {
        [weakSelf.weexView removeFromSuperview];
        weakSelf.weexView = view;
        [weakSelf.weexView setFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, kScreenWidth, kScreenHeight - [UIApplication sharedApplication].statusBarFrame.size.height - self.navigationController.navigationBar.frame.size.height - self.tabBarController.tabBar.frame.size.height)];
        [weakSelf.view addSubview:weakSelf.weexView];
    };
    
    _instance.onFailed = ^(NSError *error)
    {
        JMLog(@"%@",error);
        if (weakSelf.noDataView)
        {
            [weakSelf.noDataView removeFromSuperview];
            weakSelf.noDataView = nil;
        }
        //网络错误
        weakSelf.noDataView = [[NoDataAndErrorView alloc] initWithFrame:weakSelf.view.bounds Types:OtherErrorTypes message:@"" andBackGroundColor:[UIColor whiteColor] isShowAgainButton:YES];
        [weakSelf.view addSubview:weakSelf.noDataView];
        
        [[weakSelf.noDataView rac_signalForSelector:@selector(buttonActionWithSender:)] subscribeNext:^(RACTuple * _Nullable x)
         {
             [weakSelf refreshWeex];
         }];
    };
    
    _instance.renderFinish = ^(UIView *view)
    {
        [weakSelf _updateInstanceState:WeexInstanceAppear];
        if (weakSelf.noDataView)
        {
            [weakSelf.noDataView removeFromSuperview];
            weakSelf.noDataView = nil;
        }
    };
    
    if ([WXPrerenderManager isTaskReady:[self.sourceURL absoluteString]])
    {
        WX_MONITOR_INSTANCE_PERF_START(WXPTJSDownload, _instance);
        WX_MONITOR_INSTANCE_PERF_END(WXPTJSDownload, _instance);
        WX_MONITOR_INSTANCE_PERF_START(WXPTFirstScreenRender, _instance);
        WX_MONITOR_INSTANCE_PERF_START(WXPTAllRender, _instance);
        [WXPrerenderManager renderFromCache:[self.sourceURL absoluteString]];
        return;
    }
}
- (void)_updateInstanceState:(WXState)state
{
    if (_instance && _instance.state != state)
    {
        _instance.state = state;
        
        if (state == WeexInstanceAppear)
        {
            [[WXSDKManager bridgeMgr] fireEvent:_instance.instanceId ref:WX_SDK_ROOT_REF type:@"viewappear" params:nil domChanges:nil];
        }
        else if (state == WeexInstanceDisappear)
        {
            [[WXSDKManager bridgeMgr] fireEvent:_instance.instanceId ref:WX_SDK_ROOT_REF type:@"viewdisappear" params:nil domChanges:nil];
        }
    }
}
- (void)_appStateDidChange:(NSNotification *)notify
{
    if ([notify.name isEqualToString:@"UIApplicationDidBecomeActiveNotification"])
    {
        [self _updateInstanceState:WeexInstanceForeground];
    }
    else if([notify.name isEqualToString:@"UIApplicationDidEnterBackgroundNotification"])
    {
        [self _updateInstanceState:WeexInstanceBackground]; ;
    }
}
- (void)_addObservers
{
    for (NSString *name in @[UIApplicationDidBecomeActiveNotification,
                             UIApplicationDidEnterBackgroundNotification]) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(_appStateDidChange:)
                                                     name:name
                                                   object:nil];
    }
}
- (void)_removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值