NSTimer的基礎(chǔ)用法以及程序掛起后NSTimer仍然可以在后臺(tái)運(yùn)行計(jì)時(shí)

1. 關(guān)于NSTimer一些基本的知識(shí),網(wǎng)上應(yīng)該有很多講解,廢話不多少,直接上代碼

(1) 下面是簡(jiǎn)單的實(shí)現(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; /*定時(shí)器*/
@property (nonatomic,assign) NSInteger secondsCountDown; /*倒計(jì)時(shí)的時(shí)間數(shù)*/
@property (nonatomic,strong) UIButton* count_button; /*點(diǎn)擊的按鈕*/
@property (nonatomic,assign) NSInteger space; /*寬度*/
@property (nonatomic,assign) BOOL isClick; /*防止連續(xù)點(diǎn)擊*/

@end

@implementation NSTimerController

- (void)viewDidLoad
{
    [super viewDidLoad];
    _secondsCountDown = 20; /*初使時(shí)間20秒*/
    _space = 300; /*按鈕的寬度*/
    [self count_button];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timer invalidate]; /*將定時(shí)器從運(yùn)行循環(huán)中移除*/
    _timer = nil; /*銷毀定時(shí)器, 這樣可以避免控制器不死*/
}

-(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];

        /*注意點(diǎn):
         將計(jì)數(shù)器的repeats設(shè)置為YES的時(shí)候,self的引用計(jì)數(shù)會(huì)加1。
         因此可能會(huì)導(dǎo)致self(即viewController)不能release。
         所以,必須在viewWillAppear的時(shí)候,將計(jì)數(shù)器timer停止,否則可能會(huì)導(dǎo)致內(nèi)存泄露。*/
        
        /*手動(dòng)啟動(dòng)Runloop,然后使其在線程池里運(yùn)行*/
        /* 
         1: 下面這個(gè)方法切忌不要輕易使用,避免網(wǎng)絡(luò)請(qǐng)求的線程會(huì)被殺死:[[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

下面兩張圖是簡(jiǎn)易的效果圖:

圖1.png
圖2.png

(2) 上面的代碼中,有關(guān)于一些細(xì)節(jié)的說明,但是還有一些其他的重點(diǎn)細(xì)節(jié),在下面說下

在頁面即將消失的時(shí)候關(guān)閉定時(shí)器,之后等頁面再次打開的時(shí)候,又開啟定時(shí)器(只要是防止它在后臺(tái)運(yùn)行,暫用CPU)

-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    /*開啟繼續(xù)運(yùn)行NSTimer*/
    [_timer setFireDate:[NSDate distantPast]];
}

-(void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    /*關(guān)閉NSTimer*/
    [_timer setFireDate:[NSDate distantFuture]];
}


2. 程序掛起后NSTimer仍然可以在后臺(tái)運(yùn)行計(jì)時(shí)

具體操作如下:

步驟一: 在info里面如下設(shè)置:
info -->添加 Required background modes -->設(shè)置 App plays audio or streams audio/video using AirPlay

3C1F3F3C-6860-4A29-84C1-65554EFDF687.png

步驟二:在AppDelegate.m里面調(diào)用

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /*定時(shí)器后臺(tái)運(yùn)行*/
    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    /*設(shè)置Audio Session的Category 一般會(huì)在激活之前設(shè)置好Category和mode。但是也可以在已激活的audio session中設(shè)置,不過會(huì)在發(fā)生route change之后才會(huì)發(fā)生改變*/
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    /*激活A(yù)udio Session*/
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
 }

/*
 通過UIBackgroundTaskIdentifier可以實(shí)現(xiàn)有限時(shí)間內(nèi)在后臺(tái)運(yùn)行程序
 程序進(jìn)入后臺(tái)時(shí)調(diào)用applicationDidEnterBackground函數(shù),
 */
- (void)applicationDidEnterBackground:(UIApplication *)application{
    
    UIApplication* app = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask;
    
    /*注冊(cè)一個(gè)后臺(tái)任務(wù),告訴系統(tǒng)我們需要向系統(tǒng)借一些事件*/
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                /*銷毀后臺(tái)任務(wù)標(biāo)識(shí)符*/
                /*不管有沒有完成,結(jié)束background_task任務(wù)*/
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                /*銷毀后臺(tái)任務(wù)標(biāo)識(shí)符*/
                /*不管有沒有完成,結(jié)束background_task任務(wù)*/
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

參考如下鏈接知識(shí),深表感謝:

IOS音頻播放學(xué)習(xí)參考
IOS后臺(tái)掛起時(shí)運(yùn)行程序UIBackgroundTaskIdentifier

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容