美文网首页开开心心写代码程序员首页投稿(暂停使用,暂停投稿)
NSTimer的基础用法以及程序挂起后NSTimer仍然可以在后

NSTimer的基础用法以及程序挂起后NSTimer仍然可以在后

作者: 张付东 | 来源:发表于2016-11-29 00:01 被阅读2626次

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

下面两张图是简易的效果图:

图1.png 图2.png

(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

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

步骤二:在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;
            }
        });
    });
}

参考如下链接知识,深表感谢:

IOS音频播放学习参考
IOS后台挂起时运行程序UIBackgroundTaskIdentifier

相关文章

  • iOS-后台任务相关

    研究一波吧. 1.iOS 后台任务2.NSTimer的基础用法以及程序挂起后NSTimer仍然可以在后台运行计时3...

  • NSTimer的基础用法以及程序挂起后NSTimer仍然可以在后

    1. 关于NSTimer一些基本的知识,网上应该有很多讲解,废话不多少,直接上代码 (1) 下面是简单的实现代...

  • 防止内存泄露的NSTimer定时器

    目录 NSTimer的基础用法 NSTimer的内存泄露 安全防侧漏的定时器 NSTimer的基础用法 创建定时器...

  • NSTImer

    NSTimer 基础请参考: NSTimer的使用以及 史上最简单的,NSTimer暂停和继续 Firing a ...

  • NStimer 后台运行

    使用NSTimer的时候,每当APP进入后台,或者屏幕休眠后,NSTimer就会暂停。 要在后台NSTimer也运...

  • NSTimer

    用法 NSTimer的用法很简单,个人最常用的是下面这个方法。 [NSTimer scheduledTimerWi...

  • NStimer 后台挂起

    iOS为了让设备尽量省电,减少不必要的开销,保持系统流畅,因而对后台机制采用墓碑式的“假后台”。除了系统官方极少数...

  • iOS 延时

    1 NSTimer //1秒后执行 NSTimer *timer = [NSTimer timerWithTim...

  • NSTimer用法

    IOS NSTimer 定时器用法总结 - 珲少 的个人空间 - 开源中国社区

  • NSTimer在后台休眠问题

    当app在后台时保持NSTimer继续运行

网友评论

  • 用户3202893873:你好,这个是后台音频播放的方法,我用这个方法去实现NSTimer在后台挂起时的计时,审核被拒绝了,说是APP在后台时没有听到任何播放的声音,不知道你在用的时候有没有遇见过。
    张付东:我用的是后台挂起状态的情况下,定时器依旧在运行,按照你说的情况,你那边测试了嘛?app后台挂起状态的时候,是否有播放的声音啊?

本文标题:NSTimer的基础用法以及程序挂起后NSTimer仍然可以在后

本文链接:https://www.haomeiwen.com/subject/cimipttx.html