iOS 在闲置一段时间后执行指定动作
kevin_han 制作于 2015-09-05
1. 新建 Objective-C 类,继承 UIApplication。
2. 编辑 .h 如下
#import <UIKit/UIKit.h>
#define kApplicationTimeoutInMinutes 5
#define kApplicationDidTimeoutNotification @"APPSurplusGoods"
@interface APPSurplusGoods : UIApplication {
NSTimer *myidleTimer;
}
-(void)resetIdleTimer;
@end
3. 编辑 .m 如下:
#import "APPSurplusGoods.h"
@implementation APPSurplusGoods
// 监听所有触摸,当屏幕被触摸,时钟将被重置
-(void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
if (!myidleTimer) [self resetIdleTimer];
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
UITouchPhase phase= ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan) {
[self resetIdleTimer];
}
}
}
//重置时钟
-(void)resetIdleTimer {
if (myidleTimer) [myidleTimer invalidate];
//将超时时间由分钟转换成秒数
int timeout = kApplicationTimeoutInMinutes * 60;
myidleTimer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO];
}
//当达到超时时间,发送APPSurplusGoods通知
-(void)idleTimerExceeded {
[[NSNotificationCenter defaultCenter] postNotificationName:@"APPSurplusGoods" object:nil];
}
@end
4. 修改 main.m :
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "APPSurplusGoods.h"
int main(int argc, char *argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv,NSStringFromClass([APPSurplusGoods class]),NSStringFromClass([AppDelegate class]));
}
}
5. 接下来编辑 AppDelegate.m 文件,不需要编辑 AppDelegate.h。
#import "AppDelegate.h"
@interface AppDelegate ()
@property (nonatomic,assign) BOOL idle;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidTimeout:) name:@"APPSurplusGoods" object:nil];
return YES;
}
-(void)applicationDidTimeout:(NSNotification *)notif {
NSLog (@"time exceeded!!");
//这是故事板和xib文件不同的地方。对于你想跳转到的 View Controller,确保下面代码中的id 和故事板中 View Controller 的 Storyboard Identifier 一致。在本例中,即"mainView"。而我的故事板文件名为MainStoryboard.storyboard, 确保你的文件名和 storyboardWithName 参数保持一致。
UIViewController *controller = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:NULL]instantiateViewControllerWithIdentifier:@"mainView"];
[(UINavigationController *)self.window.rootViewController pushViewController:controller animated:YES];
}
-(void)idleTimerExceeded{
AppDelegate *appdelegate = [[UIApplication sharedApplication] delegate];
if(appdelegate.idle){
[[NSNotificationCenter defaultCenter] postNotificationName:@"APPSurplusGoods"
object:nil];
}
}