1. 關于NSTimer一些基本的知識枯怖,網(wǎng)上應該有很多講解,廢話不多少,直接上代碼
(1) 下面是簡單的實現(xiàn)代碼
#import "NSTimerController.h"
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
static const NSInteger button_tag = 100;
@interface NSTimerController ()
@property (nonatomic,strong) NSTimer* timer; /*定時器*/
@property (nonatomic,assign) NSInteger secondsCountDown; /*倒計時的時間數(shù)*/
@property (nonatomic,strong) UIButton* count_button; /*點擊的按鈕*/
@property (nonatomic,assign) NSInteger space; /*寬度*/
@property (nonatomic,assign) BOOL isClick; /*防止連續(xù)點擊*/
@end
@implementation NSTimerController
- (void)viewDidLoad
{
[super viewDidLoad];
_secondsCountDown = 20; /*初使時間20秒*/
_space = 300; /*按鈕的寬度*/
[self count_button];
}
-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[_timer invalidate]; /*將定時器從運行循環(huán)中移除*/
_timer = nil; /*銷毀定時器, 這樣可以避免控制器不死*/
}
-(UIButton*) count_button
{
if (!_count_button)
{
_count_button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.view addSubview:_count_button];
_count_button.frame = CGRectMake(SCREEN_WIDTH / 2 - 150, SCREEN_HEIGHT - 300, _space, 40);
_count_button.tag = button_tag;
_count_button.layer.cornerRadius = 5;
[_count_button setTitle:@"重新獲取" forState:UIControlStateNormal];
_count_button.backgroundColor = [UIColor orangeColor];
[_count_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_count_button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}
return _count_button;
}
-(void) buttonAction:(UIButton*) sender
{
if (!_isClick)
{
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
/*注意點:
將計數(shù)器的repeats設置為YES的時候抛寝,self的引用計數(shù)會加1。
因此可能會導致self(即viewController)不能release曙旭。
所以盗舰,必須在viewWillAppear的時候,將計數(shù)器timer停止桂躏,否則可能會導致內(nèi)存泄露钻趋。*/
/*手動啟動Runloop,然后使其在線程池里運行*/
/*
1: 下面這個方法切忌不要輕易使用,避免網(wǎng)絡請求的線程會被殺死:[[NSRunLoop currentRunLoop] run];
2: 如果想用剂习,建議如下操作:
// dispatch_async(dispatch_get_global_queue(0, 0), ^{
// _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
// [[NSRunLoop currentRunLoop] run];
});
*/
//正確用法:
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
}
-(void) timeFireMethod
{
_isClick = YES;
_secondsCountDown--;
[_count_button setTitle:[NSString stringWithFormat:@"重新獲取 (%ld)",(long)_secondsCountDown] forState:UIControlStateNormal];
[_count_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
NSLog(@"_secondsCountDown:%ld",(long)_secondsCountDown);
if (_secondsCountDown <= 0)
{
_isClick = NO;
[_timer invalidate];
_secondsCountDown = 20;
[_count_button setTitle:@"重新獲取" forState:UIControlStateNormal];
[_count_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}
}
@end
下面兩張圖是簡易的效果圖:
(2) 上面的代碼中蛮位,有關于一些細節(jié)的說明,但是還有一些其他的重點細節(jié)鳞绕,在下面說下
在頁面即將消失的時候關閉定時器失仁,之后等頁面再次打開的時候,又開啟定時器(只要是防止它在后臺運行,暫用CPU)
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
/*開啟繼續(xù)運行NSTimer*/
[_timer setFireDate:[NSDate distantPast]];
}
-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
/*關閉NSTimer*/
[_timer setFireDate:[NSDate distantFuture]];
}
2. 程序掛起后NSTimer仍然可以在后臺運行計時
具體操作如下:
步驟一: 在info里面如下設置:
info -->添加 Required background modes -->設置 App plays audio or streams audio/video using AirPlay
步驟二:在AppDelegate.m里面調用
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/*定時器后臺運行*/
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
/*設置Audio Session的Category 一般會在激活之前設置好Category和mode们何。但是也可以在已激活的audio session中設置陶因,不過會在發(fā)生route change之后才會發(fā)生改變*/
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
/*激活Audio Session*/
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
}
/*
通過UIBackgroundTaskIdentifier可以實現(xiàn)有限時間內(nèi)在后臺運行程序
程序進入后臺時調用applicationDidEnterBackground函數(shù),
*/
- (void)applicationDidEnterBackground:(UIApplication *)application{
UIApplication* app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
/*注冊一個后臺任務垂蜗,告訴系統(tǒng)我們需要向系統(tǒng)借一些事件*/
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
/*銷毀后臺任務標識符*/
/*不管有沒有完成楷扬,結束background_task任務*/
bgTask = UIBackgroundTaskInvalid;
}
});
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
/*銷毀后臺任務標識符*/
/*不管有沒有完成,結束background_task任務*/
bgTask = UIBackgroundTaskInvalid;
}
});
});
}
參考如下鏈接知識贴见,深表感謝: