main.swift中代码:
import Foundation import UIKit UIApplicationMain( CommandLine.argc,UnsafeMutableRawPointer(CommandLine.unsafeArgv) .bindMemory( to: UnsafeMutablePointer<Int8>.self,capacity: Int(CommandLine.argc)),NSStringFromClass(MyApplication.self),NSStringFromClass(AppDelegate.self) ) UIApplication.swift import Foundation import UIKit @objc(MyApplication) class MyApplication: UIApplication { override init(){ super.init(); if(_timer == nil){ _timer = Timer.scheduledTimer( timeInterval: TimeInterval(_idleSecondsTriggerlogout),target: self,selector: #selector(MyApplication.dosomething),userInfo: nil,repeats: true) } } let _idleSecondsTriggerlogout:Int = 8 * 60; // 8 mins,same with android var _timer:Timer? = nil; override func sendEvent(_ event: UIEvent) { // Ignore .Motion and .RemoteControl event simply everything else then .Touches if event.type != .touches { super.sendEvent(event) return } // .Touches only var restartTimer = true if let touches = event.allTouches { // At least one touch in progress? Do not restart timer,just invalidate it for touch in touches.enumerated() { if touch.element.phase != .cancelled && touch.element.phase != .ended { restartTimer = false break } } } if restartTimer { // Touches ended || cancelled,restart timer resetTimer() } else { // Touches in progress - !ended,!cancelled,just invalidate it //print("Touches in progress. Invalidate timer") } super.sendEvent(event) } func resetTimer() { _timer?.invalidate() _timer = Timer.scheduledTimer( timeInterval: TimeInterval(_idleSecondsTriggerlogout),repeats: true) } func dosomething(){ print("time up,logout and clear session 1"); ServiceProxy.HttpMeta.RefreshToken = ""; ServiceProxy.HttpMeta.Token = ""; ServiceProxy.HttpMeta.UserName = ""; print("time up,logout and clear session 2"); let topVC = topViewController() print("time up,logout and clear session 3"); let storyBoard : UIStoryboard = UIStoryboard(name: "Main",bundle:nil) print("time up,logout and clear session 4"); let nextViewController = storyBoard.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC print("time up,logout and clear session 5"); topVC?.present(nextViewController,animated:true,completion:nil) print("time up,logout and clear session 6"); } func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let navigationController = controller as? UINavigationController { return topViewController(controller: navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return topViewController(controller: selected) } } if let presented = controller?.presentedViewController { return topViewController(controller: presented) } return controller } }
AppDelegate.swift中代码(注释掉UIApplicationMain)
//@UIApplicationMain
info.plist中代码:
<key>Principal class</key> <string>MyApplication</string>