iPhone: 检查用户最后一次触摸屏幕的时间

来源:未知 责任编辑:责任编辑 发表时间:2014-01-20 07:51 点击:

方案一:让你的应用程序委托子类化 UIApplication。在实现部分,覆盖 sendEvent:方法:

- (void)sendEvent:(UIEvent *)event {

     [super sendEvent:event];

      // 只在开始或结束触摸时 reset 闲置时间, 以减少不必须要的时钟 reset 动作

     NSSet *allTouches = [event allTouches];

     if ([allTouches count] > 0) {

         // allTouchescount 似乎只会是 1, 因此 anyObject 总是可用的

        UITouchPhase phase =((UITouch *)[allTouches anyObject]).phase;

         if (phase ==UITouchPhaseBegan || phase == UITouchPhaseEnded)

            [self resetIdleTimer];

     }

}

- (void)resetIdleTimer {

     if (idleTimer) {

         [idleTimerinvalidate];

         [idleTimerrelease];

     }

     idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTimetarget:self selector:@selector(idleTimerExceeded) userInfo:nil repeats:NO]retain];

}

- (void)idleTimerExceeded {

     NSLog(@"idle time exceeded");

}

这里, maxIdleTime 和 idleTimer 都是实例变量.

此外你要修改 main.m,告诉 UIApplicationMain 使用你的 delegate 类(在这个例子里,即 AppDelegate)作为主类:

int main(int argc, char *argv[])

{

    @autoreleasepool{

       return UIApplicationMain(argc, argv, NSStringFromClass([AppDelegateclass]), NSStringFromClass([AppDelegate class]));

    }

}

方案二:本方案不需要子类化UIApplication。它能在某个 UIViewController 子类上生效,因此对于只有一个 ViewController(比如一个互动式应用或游戏)相当有用,或者只想在一个 View Controller 中处理用户闲置时间。

它不会在重置时钟时重建 NSTimer 对象,而仅仅是修改它的触发时间。

在你的代码中,你可以调用 resetIdleTimer 去检测各种事件(比如加速计的急剧改变)。

@interface MainViewController : UIViewController {

     NSTimer*idleTimer;

}

@end 

#define kMaxIdleTimeSeconds 60.0

@implementation MainViewController

#pragma mark -

#pragma mark Handling idle timeout

- (void)resetIdleTimer {

     if(!idleTimer) {

         idleTimer =[[NSTimer scheduledTimerWithTimeInterval:kMaxIdleTimeSeconds                                                      target:self                                                    selector:@selector(idleTimerExceeded)                                                    userInfo:nil                                                     repeats:NO] retain];

发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码:点击我更换图片
最新评论 更多>>

推荐热点

  • Lexical or Preprocessor Issue 'xxx.h
  • ios学习笔记(二)xcode 4.3.2下实现基本交互
  • ios版本的helloworld
  • iphone(object-c) 内存管理(3) 有效的内存管理 前半部分
  • ios学习笔记(一)xcode 4.3.2下创建第一个ios项目
  • IOS类似iphone通讯录TableView的完整demo【附源码】
  • UITableView一些方法
  • [iPhone中级]iPhone团购信息客户端的开发 (二)
  • 如何为Iphone应用创建启动界面
网站首页 - 友情链接 - 网站地图 - TAG标签 - RSS订阅 - 内容搜索
Copyright © 2008-2015 计算机技术学习交流网. 版权所有

豫ICP备11007008号-1