从应用程序扩展中显示 UIAlertController

问题描述

我正在开发适用于 iOS 的消息过滤器扩展程序,但有点卡住了。我希望能够在收到新消息并将其归类为垃圾邮件显示 UIAlertController。
到目前为止我尝试过的代码(在扩展的handle方法中):

dispatchQueue.main.async {
     let alertController = UIAlertController(title: " TITLE ",message: " MESSAGE ",preferredStyle: UIAlertController.Style.alert)
     alertController.addAction(UIAlertAction(title: "Close",style: UIAlertAction.Style.cancel,handler: nil))
     let alertwindow = UIWindow(frame: UIScreen.init().bounds)
     alertwindow.rootViewController = UIViewController()
     alertwindow.windowLevel = UIWindow.Level.alert + 1;
     alertwindow.makeKeyAndVisible()
     alertwindow.rootViewController?.present(alertController,animated: true,completion: nil)
}

所以我的问题是:考虑到即使应用程序本身关闭,过滤器也可以工作,是否可以在消息过滤器扩展中显示 UIAlertController? (如果是这样,我在上述实现中缺少什么?)

解决方法

您需要一个 UIWindow 来展示您的 UIAlertController,但您刚刚创建了一个未附加的 UIViewController对任何事情。所以你绝对不能在扩展中显示 UIAlertController