美文网首页iOS 开发 iOS Developer
iOS开发之登录超时自动退出,计算时间差

iOS开发之登录超时自动退出,计算时间差

作者: Ego_1973 | 来源:发表于2016-09-22 15:26 被阅读0次

    // 此方法适用于所有被创建过的controller,且当前controller生命周期存在,如有错误的地方望大神斧正

    // 说一下我们的需求和实现原理,需求:在点击home键退出但没有滑飞它,5分钟之后需要重新登录(其实和平安一账通的登录很像) ;实现原理:添加观察者,不用我们手动发送通知,系统会自动发送通知,计算时间差,然后就可以啦😆

    // 贴代码图片


    屏幕快照 2016-09-22 下午2.54.31.png

    // 我是控制的300s,就是5分钟,超过就弹个框,点击后退出


    屏幕快照 2016-09-22 下午3.23.01.png

    // 贴代码

    • (void)viewWillAppear:(BOOL)animated {
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackgroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
      }

    • (void)appDidEnterBackgroundNotification{
      NSDate *date = [NSDate date];
      NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
      [user setObject:date forKey:K_LOGOUTTIME_KEY];
      [user synchronize];
      NSLog(@"存储时间 =============== ======= %@",date);
      }

    • (void)appWillEnterForegroundNotification {
      NSDate *dateLast = [[NSUserDefaults standardUserDefaults] objectForKey:K_LOGOUTTIME_KEY];
      NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
      [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
      NSString *strDate = [dateFormatter stringFromDate:dateLast];
      [self intervalSinceNow:strDate];
      }

    // 计算某一时间到当前时间

    • (NSString *)intervalSinceNow: (NSString *) theDate
      {
      NSArray timeArray=[theDate componentsSeparatedByString:@"."];
      theDate=[timeArray objectAtIndex:0];
      NSDateFormatter date=[[NSDateFormatter alloc] init];
      [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
      NSDate d=[date dateFromString:theDate];
      NSTimeInterval late=[d timeIntervalSince1970]
      1;
      NSDate
      dat = [NSDate date];
      NSTimeInterval now=[dat timeIntervalSince1970]
      1;
      NSString *timeString=@"";
      NSTimeInterval cha= fabs(late-now); // 求绝对值
      timeString = [NSString stringWithFormat:@"%f", cha];
      timeString = [timeString substringToIndex:timeString.length-7];
      if ([timeString intValue] > 300) {
      HPAlertController *alert = [[HPAlertController alloc]initWithViewController:self];
      AlertData *data = [AlertData alertDataTarget:self Title:@"提示" message:@"您登录超时了哦~" itemTitleSelectorStrPairs:@"确认",@"ensureLogAgain",nil];
      [alert showAlertWithData:data];
      }
      return timeString;
      }

    • (void)ensureLogAgain {
      [self logoutViewController];

    }

    // 如果监听通知写在viewDidLoad里面,就不用再移除啦

    • (void)viewDidDisappear:(BOOL)animated {
      [[NSNotificationCenter defaultCenter]removeObserver:self];
      }

    相关文章

      网友评论

        本文标题:iOS开发之登录超时自动退出,计算时间差

        本文链接:https://www.haomeiwen.com/subject/lzyzettx.html