当用户按home键退出到后台时,对于安全性要求较高的App,我们通常会对它进行页面超时处理,按正常处理方式,可能会这样写:
在AppDelegate.m中:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
//进入后台计时
[UserInfo sharedUserInfo].enterBackgroundTime = [NSDate date];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
BOOL isLogin = [UserInfo sharedUserInfo].isLogin;
NSDate *date = [UserInfo sharedUserInfo].enterBackgroundTime;
if (isLogin && date) {
NSCalendar *cal = [NSCalendar currentCalendar];
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlags fromDate:date toDate:[NSDate date] options:0];
long sec = [d hour] * 3600 + [d minute] * 60 + [d second];
//判断时间有没有超时,没有超时的话,重新设置登录时间
if (sec >= 600) {
// 进入超时页面,不再细述。。。。。
} else {
[UserInfo sharedUserInfo].enterBackgroundTime = [NSDate date];
}
}
}
其中UserInfo.h定义:
@property (nonatomic,strong) NSDate *enterBackgroundTime; //超时时间相关
方法2:
//
// AppDelegate.m
// Test
//
// Created by lvxiangan on 4/21/16.
// Copyright © 2016 lvxiangan. All rights reserved.
//
#import "AppDelegate.h"
@interface AppDelegate ()
@property (assign, nonatomic) UIBackgroundTaskIdentifier bgTaskId; // 后台任务标记
@property (strong, nonatomic) dispatch_block_t expirationHandler;
@property (assign, nonatomic) BOOL background;
@property (assign, nonatomic) BOOL isLogined;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIApplication* app = [UIApplication sharedApplication];
// 数据模拟
self.isLogined = YES;
__weak AppDelegate* weakSelf = self;
// 创建后台自唤醒,当180s时间结束的时候系统会调用这里面的方法
self.expirationHandler = ^{
[app endBackgroundTask:weakSelf.bgTaskId];
weakSelf.bgTaskId = UIBackgroundTaskInvalid;
NSLog(@"Expired,处理超时。。。。。");
};
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
self.background = NO;
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// 当登陆状态才启动后台操作
if (self.isLogined)
{
NSLog(@"Entered background");
self.bgTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:self.expirationHandler];
self.background = YES;
}
}
同时发现所有App都存在这个问题:
当用户双击Home键,看到的是超时前的页面A,重新进入app后看到的却是超时页面B。