您的位置:首页 > Web前端 > React

React-Native项目中消除启动时的白屏(闪白)--(iOS)

2017-02-08 22:06 453 查看
做过 RN 项目的童鞋应该都知道 RN 项目启动之后有一个短暂的白屏,调试阶段这个白屏的时间较长,大概3-5秒,打正式包后这个白屏时间会大大缩短,大多时候都是一闪而过,所以称之为『闪白』。



虽然说时间很短,但是只要能被用户察觉,都是属于 Bug


为什么会有白屏

在iOS App 中有 启动图(LaunchImage),启动图结束后才会出现上述的闪白,这个过程是 JS 解释的过程,JS 解释完毕之前没有内容,所以才表现出白屏,那么解决的方法就是在启动图结束后,JS 解释完成前,做一些处理

启动图结束的时间
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;


JS解释完毕

可以大致确定在项目第一个页面加载完毕,注意是第一个页面,不一定是 app 的『首页』
componentDidMount() {

}



解决思路

启动图结束后通过原生代码加载一张全屏占位图片,跟启动图一样的图片,混淆视听『欺骗用户』
JS解释完毕后通知原生可以移除占位图
收到 JS 发来的可以移除占位图的通知,移除占位图


实现

SplashScreen 用来接收 JS 发来的『移除占位图』的消息

SplashScreen.h
#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
@interface SplashScreen : NSObject<RCTBridgeModule>

@end


SplashScreen.m
#import "SplashScreen.h"
@implementation SplashScreen

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(close){
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_CLOSE_SPLASH_SCREEN" object:nil];
}
@end


AppDelegate.m
@interface AppDelegate ()
{
UIImageView *splashImage;
}
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeSplashImage) name:"Notification_CLOSE_SPLASH_SCREEN" object:nil];

...
[self autoSplashScreen];//写在 return YES 之前,其他代码之后
return YES;
}
-(void)autoSplashScreen {
if (!splashImage) {
splashImage = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
}
if (IPHONESCREEN3p5) {
[splashImage setImage:[UIImage imageNamed:@"launch4"]];
}else if (IPHONESCREEN4){
[splashImage setImage:[UIImage imageNamed:@"launch5"]];
}else if (IPHONESCREEN4p7){
[splashImage setImage:[UIImage imageNamed:@"launch6"]];
}else if (IPHONESCREEN5p5){
[splashImage setImage:[UIImage imageNamed:@"launch7"]];
}
[self.window addSubview:splashImage];
}
-(void)closeSplashImage {
dispatch_sync(dispatch_get_main_queue(), ^{
[UIView animateWithDuration:0.5 animations:^{
splashImage.alpha = 0;
} completion:^(BOOL finished){
[splashImage removeFromSuperview];
}];
});
}


JS中选择合适的时机调用关闭方法
if (Platform.OS === 'ios') {
NativeModules.SplashScreen.close();
};


GitHub上有一套统一两个平台的代码,有兴趣的可以去看看,
https://github.com/crazycodeboy/react-native-splash-screen/blob/master/README.zh.md
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: