IOS以及H5的在APP前后台切换处理

今天在开发过程中遇到一个问题,APP有一个加载的效果,是一个循环的动画,在APP切换到后台后再切换回来,动画就停止了~ 因为加载效果使用的是第三方的库,无法进行问题的排查和修复~(啊,还是觉得前端好,npm安装的依赖库的代码即使压缩过,努努力还是能看懂了解问题出在那里。。。IOS这种AOT编译除非去反编译那是真没办法)
OK,虽然是新手,但总得解决这个问题是不~ 既然和切换前后台有关系,那就通过这里下手,首先去学习了IOS的应用程序状态:

application:willFinishLaunchingWithOptions:   应App刚打开的时候调用
本地通知:UIApplicationDidFinishLaunchingNotification

application:didFinishLaunchingWithOptions:  App被展示之前调用该事件作一些初始化工作
本地通知:UIApplicationDidFinishLaunchingNotification

applicationDidBecomeActive:  App被切换到前台状态的预处理
本地通知:UIApplicationDidBecomeActiveNotification

applicationWillResignActive:   App从前台状态切换到其他状态时执行
本地通知:UIApplicationWillResignActiveNotification

applicationDidEnterBackground:   App切换到后台,并且可能随时被挂起
本地通知:UIApplicationDidEnterBackgroundNotification

applicationWillEnterForeground:   App从后台切换到前台,但是还没有Active
本地通知:UIApplicationWillEnterForegroundNotification

applicationWillTerminate:   App被终止,在App被挂起的时候会调用该方法
本地通知:UIApplicationWillTerminateNotification

因此通过监听通知中心的UIApplicationDidEnterBackgroundNotification和UIApplicationDidBecomeActiveNotification通知就可以了。剩下的就非常简单了:


-(void)pageInit{
    ...
    [self initLoading];

    ...
}

-(void)initLoading{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideLoading) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoading) name:UIApplicationWillEnterForegroundNotification object:nil];

    [self showLoading];
}

-(void)removeLoading{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)showLoading{
    self.loadingView=[LoadingView new];
    [self.view addSubview:self.loadingView];
}

-(void)hideLoading{
    [self.loadingView removeFromSuperview];
    self.loadingView=nil;
}

关于H5:
一直做的web端开发,在解决自然会想起如果是H5页面有一个功能正在执行(比如定时器),APP切换到后台后定时器是否还是在继续执行呢。查找资料后答案是否定的,那如何在H5中判断APP是否切换到后台呢:

//添加visibilitychange事件监听
document.addEventListener('visibilitychange',function(){
    // hidden为切换到后台或者锁屏状态,visible为重新显示状态
    if(document.visibilityState === 'hidden'){
    } else if(document.visibilityState === 'visible'){
    }
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容