重写application使app无操作后执行清理工作

作者: shaneZhang 分类: ios技术 发布时间: 2015-01-16 15:41

1重写application类,拦截应用的所有响应事件

2 修改main类,使用自定义的application类

3 在需要的类中进行拦截

核心代码

//  FFApplication.m
//  TouchEventDemo
//
//  Created by shanezhang on 15/1/16.
//  Copyright (c) 2015年 shanezhang. All rights reserved.
//

#import "FFApplication.h"

@interface FFApplication()
{
NSTimer *_timer;
}
@end

@implementation FFApplication


/**
 *  重新响应事件的方法
 *
 *  @param event 事件响应
 */
 - (void)sendEvent:(UIEvent *)event
 {
[super sendEvent:event];

if (_timer == nil)
{
    // 重置
    [self restTimer];
}

NSSet *allTouches = [event allTouches];

if (allTouches.count > 0)
{
    UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
    // 重置
    if (phase == UITouchPhaseBegan)
    {
        [self restTimer];
    }
}
 }

// 重置定时器
- (void)restTimer
{
if (_timer != nil)
{
    // 终止计时器
    [_timer invalidate];
}

// 将超时时间转换成秒数
NSInteger timeout = kApplicationTimeoutInMinutes * 60;

_timer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self    

 selector:@selector(timeOut) userInfo:nil repeats:NO];

}

/**
 *  超时执行的通知
 */
- (void)timeOut
{
[[NSNotificationCenter defaultCenter]postNotificationName:
kApplicationDidTimeoutNotification object:nil];
}
@end

演示代码传送门

本页面支持繁体中文友好显示:重写application使app无操作后执行清理工作

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复