最近做项目,要求制作一个全局session
解释一下,就是软件在60s无任何操作的时候,会调用手势锁屏功能,说实话,这个功能很鸡肋,往往要以消耗软件性能为代价,下面讲讲我的方案
思路如下:
制作一个定时器,这个定时器在60秒后会触发手势页面弹出。
但如果用户有操作,定时器不断更新时间,即每次操作,都会重置一个60秒
同时我自己觉得这应该是一个单例模式,因为整个系统只能有一个定时器,否则就乱套了。
现在贴出相关代码,由于是自己写的,也许可能并不是很完善。
#import <Foundation/Foundation.h>
@interface PXJNSNotificationTimeOut : NSObject{
dispatch_queue_t myQueue;
}
@property(atomic,strong)__block NSDate *timeOut;
@property(atomic,strong)NSTimer *timer;
+ (PXJNSNotificationTimeOut *)instance;
- (void)PostSeesionNotification;
@end
#import "PXJNSNotificationTimeOut.h"
#import "GesturePasswordController.h"
#define sessionTime 60.0
static PXJNSNotificationTimeOut *notificationTimeOut = nil;
@implementation PXJNSNotificationTimeOut
- (id)init{
if (self = [super init]) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:sessionTime target:self selector:@selector(TimeOutController) userInfo:nil repeats:NO];
}
return self;
}
+ (PXJNSNotificationTimeOut *)instance{
if (notificationTimeOut == nil) {
@synchronized(self) {
if (notificationTimeOut == nil) {
notificationTimeOut = [[self alloc] init];
}
}
}
return notificationTimeOut;
}
- (void)PostSeesionNotification{
[self.timer invalidate];//从runloop中移除,暂停计时器,timer=nil
self.timer = [NSTimer scheduledTimerWithTimeInterval:sessionTime target:self selector:@selector(TimeOutController) userInfo:nil repeats:NO];
}
//注意最好异步操作,否则程序卡死了
//同时注意dispatch_get_main_queue()很重要,否则容易造成你弹出的页面不完整,其实是页面显示不及时,个人觉得
- (void)TimeOutController{
dispatch_async(dispatch_get_main_queue(), ^{
GesturePasswordController *gesture = [[GesturePasswordController alloc] initWithNibName:nil bundle:nil];
gesture.isDownLoginData = NO;
gesture.comefromType = otherType;
gesture.hidesBottomBarWhenPushed = YES;
UIViewController *vc = [self getCurrentViewController];
if ([vc isKindOfClass:[GesturePasswordController class]]) {
}else{
[vc presentViewController:gesture animated:YES completion:NULL];
}
});
}
//得到当前页面,以便于弹出手势页面
- (UIViewController *)getCurrentViewController{
UIViewController *result = nil;
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for (UIWindow *tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
UIWindow *frontWindow = [[window subviews] objectAtIndex:0];
id nextResponder = [frontWindow nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]]) {
result = nextResponder;
}else{
result = window.rootViewController;
}
return result;
}
@end
你以为这样就完了吗?no,no,no
其实更困难的在于布码,要讲这件事情不属于你的程序相关的所有位置,即用户的触发都能调动这件事情,简直了
所以此时感觉你的程序的所有controller有一个超级基类十分重要,否则,部码极其困难。