当用户在应用程序中锁定设备时如何处理我的应用程序

How can I handle my app when user lock device in application

我正在为我的应用程序使用 XMPPframework 来获取消息问题是当应用程序处于 运行 时用户锁定设备然后再次解锁时 XMPPStream 与服务器断开连接并变得无用但当用户只需按主页按钮(当用户再次进入应用程序时,XMPP 开始重新连接,这很好!)我搜索了网络,发现在设备被锁定之前调用了此方法:

func applicationWillResignActive(_ application: UIApplication) {

    print("i am in will resign")
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {

    print("i am in background")
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

我想在我的 viewcontroller 用户锁定设备中实现此方法和 didbecomeactive 方法我只是将其放在我的 vc 但没有成功:

class ViewController: x ,UIApplicationDelegate {

func applicationWillResignActive(_ application: UIApplication) {

    print("frommmm vc i am in will resign")

}
}

我知道是因为我没有给 vc 委托,但我该怎么做,或者我还能为我的问题做些什么? 提前致谢

您不能只将 UIApplicationDelegate 添加到任何视图中来调用它。

在您的 AppDelegate.swift

中使用协议 UIApplicationDelegate 中定义的方法

PS: 如果您想深入了解自己的观点,那么您必须遵循

中的建议