iPhone: Detecting user inactivity/idle time since last screen touch

前端 未结 9 1399
我寻月下人不归
我寻月下人不归 2020-11-22 17:10

Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I\'m trying to figure out the best way t

9条回答
  •  温柔的废话
    2020-11-22 17:19

    I have a variation of the idle timer solution which doesn't require subclassing UIApplication. It works on a specific UIViewController subclass, so is useful if you only have one view controller (like an interactive app or game may have) or only want to handle idle timeout in a specific view controller.

    It also does not re-create the NSTimer object every time the idle timer is reset. It only creates a new one if the timer fires.

    Your code can call resetIdleTimer for any other events that may need to invalidate the idle timer (such as significant accelerometer input).

    @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];
        }
        else {
            if (fabs([idleTimer.fireDate timeIntervalSinceNow]) < kMaxIdleTimeSeconds-1.0) {
                [idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:kMaxIdleTimeSeconds]];
            }
        }
    }
    
    - (void)idleTimerExceeded {
        [idleTimer release]; idleTimer = nil;
        [self startScreenSaverOrSomethingInteresting];
        [self resetIdleTimer];
    }
    
    - (UIResponder *)nextResponder {
        [self resetIdleTimer];
        return [super nextResponder];
    }
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self resetIdleTimer];
    }
    
    @end
    

    (memory cleanup code excluded for brevity.)

提交回复
热议问题