现在一些app为了考虑用户信息安全,会加上一些安全设置,多数见于银行类的APP。
APP退到后台时间处理
这个比较简单,只要把退到后台时间存储到本地,打开时再取当前时间,进行比较,需要注意的点是:在程序被杀死时要将时间清空。
- (void)applicationDidEnterBackground:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
[[NSUserDefaults standardUserDefaults] setValue:[NSString getNowTimeTimestamp2] forKey:@"EnterBackgroundTime"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
NSString *enterBackgroundTime = [[NSUserDefaults standardUserDefaults] valueForKey:@"EnterBackgroundTime"];
if (enterBackgroundTime.length > 5) {
NSTimeInterval value = [[NSString getNowTimeTimestamp2] floatValue] - [enterBackgroundTime floatValue];
int minute = (int)value /60%60;
if (minute >= 30) {
[self gesturesPasswordView];
}
}
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"kUserEnterFreeTimeoutNotification" object:nil];
[[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"EnterBackgroundTime"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
APP长时间未操作
这个比较好的方法是给UIApplication建一个分类,在分类里重写sendEvent方法,来对事件进行监听
@interface SJApplication : UIApplication
@property (nonatomic,strong) NSTimer *myTimer;
- (void)resetTimer;
@end
.m
#define kApplicationTimeoutInMinutes 30
#import "SJApplication.h"
@implementation SJApplication
- (void)sendEvent:(UIEvent *)event {
[super sendEvent:event];
if (!_myTimer) {
[self resetTimer];
}
NSSet *allTouches = [event allTouches];
if ([allTouches count] > 0) {
UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) {
[self resetTimer];
}
}
}
//重置时钟
- (void)resetTimer {
if (_myTimer) {
[_myTimer invalidate];
}
int timeout =kApplicationTimeoutInMinutes * 60;//超时时间 分钟,
_myTimer = [NSTimer scheduledTimerWithTimeInterval:timeout target:self selector:@selector(freeTimerNotificate:) userInfo:nil repeats:NO];
}
//当达到超时时间,发送 kApplicationTimeoutInMinutes通知
- (void)freeTimerNotificate:(NSNotification *)notification {
//在想要获得通知的地方注册这个通知就行了
[[NSNotificationCenter defaultCenter] postNotificationName:@"kUserEnterFreeTimeoutNotification"object:nil];
}
@end
AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gesturesPasswordView) name:@"kUserEnterFreeTimeoutNotification"object:nil];
return YES;
}
- (void)gesturesPasswordView {
}