In the development of iOS, sometimes it is necessary to make a screen saver function for the sake of aesthetics, the main thing is that if the app runs without touching the screen for a period of time, the app will play screen-protected content, and when the screen is touched, the screen saver disappears, the program continues to run,
The first implementation detects whether there is a touch screen, then we need to use the UIWindow instance method
-(void) Sendevent: (uievent *) event to detect whether the screen is touching
Define a subclass of UIWindow
#import <UIKit/UIKit.h>
@class mainviewcontroller,screenprotectviewcontroller;
@interface Applicationwindow:UIWindow
@property (nonatomic,strong)nstimer *idletimer;
@property (nonatomic,strong)mainviewcontroller *MAINVC;
@property (nonatomic,strong)uinavigationcontroller *NAVC;
@property (nonatomic,strong) Screenprotectviewcontroller *SCREENPROTECTVC;
@end
#import "ApplicationWindow.h"
#import "MainViewController.h"
#import "ScreenProtectViewController.h"
@implementation Applicationwindow
@synthesize IDLETIMER,MAINVC,SCREENPROTECTVC,NAVC;
-(ID) initWithFrame: (cgrect) frame
{
self = [superinitwithframe: frame];
if (self) {
//initialization code
MAINVC = [mainviewcontrollershareinstance];
NAVC = [[uinavigationcontrolleralloc] Initwithrootviewcon Troller:mainvc];
}
return self;
}
-(void) Sendevent: (uievent *) event {//Detection screen on no touch action
[Supersendevent: event];
// reset idle time only at start or end of touch to reduce the clock reset action not required
nsset *alltouches = [Event alltouches];
if ([Alltouches count] >0) {
//Alltouchescount seems to only be 1, so Anyobject is always available
uitouchphase Phase = ((uitouch *) [alltouchesanyobject]). phase;
if (phase = =Uitouchphasebegan | | phase = =uitouchphaseended)
[selfresetidletimer];
}
}
-(void) Resetidletimer {
if (Idletimer) {
[idletimerinvalidate];
NSLog(@ "Noprotect");
self. Rootviewcontroller =navc; Enter the mode in which the program is running
}
idletimer = [ nstimer Scheduledtimerwithtimeinterval: 5 target: self selector: @ Selector (idletimerexceeded) userinfo: nil Repeats : no ];
Here you can set the time interval at which screen protection occurs
}
-(void) idletimerexceeded {
NSLog(@ "Screenprotect");
SCREENPROTECTVC = [screenprotectviewcontrollershareinstance];
self. Rootviewcontroller =screenprotectvc; Go to screen saver mode
}
@end
The implementation of this function is mainly the use of UIWIONDW hierarchical relationship, there is uiwidow to detect the operation of the screen touch method, not much to say, directly on the code bar
Demo
The magical function of UIWindow (ii) screen protection for the production app