我們知道洋丐,當(dāng)程序進(jìn)入后臺(tái)時(shí)告嘲,計(jì)時(shí)器就會(huì)暫時(shí)停止翩剪,當(dāng)重新進(jìn)入程序時(shí)挟裂,計(jì)時(shí)器又會(huì)重新開(kāi)始粘室,有時(shí)候蔑鹦,我們需要在程序進(jìn)入后臺(tái)時(shí)歼狼,計(jì)時(shí)器依然能夠計(jì)時(shí)裤翩,所以拳亿,就想到了一種解決方案晴股,利用進(jìn)入后臺(tái)和前臺(tái)的時(shí)間差來(lái)讓計(jì)時(shí)器完美計(jì)時(shí)。
? ? ? 首先在app delegate.m中有幾個(gè)方法肺魁,這里我們用的是一下2個(gè)方法
//當(dāng)程序進(jìn)入后臺(tái)的時(shí)候調(diào)用
- (void)applicationWillResignActive:(UIApplication *)application;
//當(dāng)程序進(jìn)入前臺(tái)的時(shí)候調(diào)用
- (void)applicationDidBecomeActive:(UIApplication *)application;
所以當(dāng)程序進(jìn)入后臺(tái)的時(shí)候电湘,我們可以注冊(cè)一個(gè)通知,這個(gè)通知用來(lái)告訴對(duì)應(yīng)的VC“程序已經(jīng)進(jìn)入后臺(tái),記錄當(dāng)前的系統(tǒng)時(shí)間”寂呛,
- (void)applicationWillResignActive:(UIApplication *)application{
? ? [[NSNotificationCenter defaultCenter] postNotificationName:@"程序進(jìn)入后臺(tái)" object:nil];
}
同樣在程序再次進(jìn)入前臺(tái)的時(shí)候記錄當(dāng)前的時(shí)間
- (void)applicationDidBecomeActive:(UIApplication *)application{
? ? ? ? [[NSNotificationCenter defaultCenter] postNotificationName:@"程序進(jìn)入前臺(tái)" object:nil];
}
在對(duì)應(yīng)的VC.m中接收通知,先聲明一個(gè)全局的變量怎诫,NSDate * goBackgroundDate;
-(void)viewWillAppear:(BOOL)animated{
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBackgroud) name:@"程序進(jìn)入后臺(tái)" object:nil];
? ? [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoForegroud) name:@"程序進(jìn)入前臺(tái)" object:nil];
}
- (void)appGoBackgroud{
? ? goBackgroundDate = [NSDate date];
}
- (void)appGoForegroud{
? ? NSTimeInterval ?timeGone = [[NSDate date] timeIntervalSinceDate:goBackgroundDate];
? time = timeGone + time;
}
- (void)dealloc{
? ? ?[[NSNotificationCenter defaultCenter]removeObserver:self];
}
以上就為后臺(tái)運(yùn)行計(jì)時(shí)器的解決方法,time為你自己定義的時(shí)間變量昧谊,timeGone為時(shí)間間隔刽虹。也可以參考原文:iOS鎖屏計(jì)時(shí)器處理? 我只是在原作者的基礎(chǔ)上,動(dòng)手實(shí)現(xiàn)了一下呢诬。