1. 关于NSTimer一些基本的知识,网上应该有很多讲解,废话不多少,直接上代码
(1) 下面是简单的实现代码
#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; /*倒计时的时间数*/
@property (nonatomic,strong) UIButton* count_button; /*点击的按钮*/
@property (nonatomic,assign) NSInteger space; /*宽度*/
@property (nonatomic,assign) BOOL isClick; /*防止连续点击*/
@end
@implementation NSTimerController
- (void)viewDidLoad
{
[super viewDidLoad];
_secondsCountDown = 20; /*初使时间20秒*/
_space = 300; /*按钮的宽度*/
[self count_button];
}
-(void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[_timer invalidate]; /*将定时器从运行循环中移除*/
_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];
/*注意点:
将计数器的repeats设置为YES的时候,self的引用计数会加1。
因此可能会导致self(即viewController)不能release。
所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。*/
/*手动启动Runloop,然后使其在线程池里运行*/
/*
1: 下面这个方法切忌不要轻易使用,避免网络请求的线程会被杀死:[[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) 上面的代码中,有关于一些细节的说明,但是还有一些其他的重点细节,在下面说下
在页面即将消失的时候关闭定时器,之后等页面再次打开的时候,又开启定时器(只要是防止它在后台运行,暂用CPU)
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
/*开启继续运行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中设置,不过会在发生route change之后才会发生改变*/
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
/*激活Audio Session*/
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
}
/*
通过UIBackgroundTaskIdentifier可以实现有限时间内在后台运行程序
程序进入后台时调用applicationDidEnterBackground函数,
*/
- (void)applicationDidEnterBackground:(UIApplication *)application{
UIApplication* app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
/*注册一个后台任务,告诉系统我们需要向系统借一些事件*/
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;
}
});
});
}
参考如下链接知识,深表感谢: