通过触摸Swift来检测应用程序何时处于活动状态或不活动状态

什么代码可以用来检测用户何时与应用程序进行交互,以及用户何时不与应用程序进行交互?

目前,我有一个ViewControllerUIView接收触摸覆盖触摸,也通过接收平移手势和轻敲手势。 这个问题的解决scheme需要与当前的手势分开,或者坐在这些手势之上。

是否有一个手势识别器,可以告诉我的应用何时收到手势,什么时候没有收到手势?

当应用程序处于活动状态时,是否有一种方法可以监视应用程序是否正在接收触摸,何时不触摸并根据需要调用某个function,例如:

 func appActive(){ print("App received input from a touch, tap, swipe, long press etc.") } func appInactive(){ print("App stopped receiving any input.") } 

谢谢。

Swift 2. Xcode 7.2。 testingiOS 7 – 9。

改编自: 如何使用Swift检测Swift 2 Subclass UIApplication中的 所有接触


1 – find您的项目的Swift文件AppDelegate.swift ,并注释掉@UIApplicationMain

 //@UIApplicationMain 

2 – 将一个新的Swift文件添加到名为完全main.swift的项目中,并添加代码:

 import UIKit UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate)) 

3 – 将一个新的Swift文件添加到名为UIApplication.swift的项目中,然后添加代码:

 import UIKit @objc(MyApplication) class MyApplication: UIApplication { 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.enumerate() { if touch.element.phase != .Cancelled && touch.element.phase != .Ended { restartTimer = false break } } } if restartTimer { // Touches ended || cancelled, restart timer print("Touches ended. Restart timer") } else { // Touches in progress - !ended, !cancelled, just invalidate it print("Touches in progress. Invalidate timer") } super.sendEvent(event) } } 

4 – find您的项目的Info.plist文件,并添加一个新的键(Xcode菜单: Editor > Add Item ,select或键入关键的Principal class ,具有string值MyApplication

在这里输入图像说明


5 – 运行你的项目!


拦截应用程序触摸的一种方法是创build一个自定义UIWindow,它将捕获触摸而不取消它们。

 class CustomWindow: UIWindow { override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { // Do any action you would like to perform to indicate the application is active return false } } 

您必须在应用程序委托中添加此窗口,并将其级别设置在主窗口上方。

 @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var topWindow: CustomWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { topWindow = CustomWindow(frame: UIScreen.mainScreen().bounds) topWindow?.rootViewController = UIViewController() topWindow?.windowLevel = UIWindowLevelNormal + 1 topWindow?.hidden = false return true }