iOS之超时页面处理

74 篇文章 7 订阅
46 篇文章 1 订阅

   当用户按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。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值