当应用程序从iOS中的本地通知进入前景时触发特定的操作? (使用swift)

我正在使用新的语言Swift构build一个iOS应用程序。 现在它是一个HTML5应用程序,它使用UIWebView显示HTML内容。 该应用程序有本地通知,而我想要做的就是在应用程序通过点击(触摸)本地通知进入前景时在UIWebView中触发一个特定的javascript方法。

我已经看过这个问题 ,但似乎并没有解决我的问题。 我也遇到这个问题 ,告诉我使用UIApplicationState,这是好的,这将帮助我知道应用程序从通知进入前台。 但是,当应用程序恢复,如何调用应用程序恢复时显示的视图的viewController中的方法?

我想要做的是得到我的ViewController的一个实例,并在其中设置一个属性为true。 如下所示

class FirstViewController: UIViewController,UIWebViewDelegate { var execute:Bool = false; @IBOutlet var tasksView: UIWebView! } 

而在我的AppDelegate我有方法

 func applicationWillEnterForeground(application: UIApplication!) { let viewController = self.window!.rootViewController; let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("FirstView") as FirstViewController setViewController.execute = true; } 

所以我想要做的是当应用程序再次进入前台时,我想查看执行variables并运行方法如下,

 if execute{ tasksView.stringByEvaluatingJavaScriptFromString("document.getElementById('sample').click()"); } 

我应该把逻辑代码放在哪里,从webview触发javascript? 它会在viewDidLoad方法,或者其中一个webView委托方法? 我已经尝试将该代码放在viewDidLoad方法中,但布尔值执行的值被设置为其初始值,而不是在应用程序进入前台时在委托中设置的值。

如果我希望在应用程序返回前台时通知视图控制器,则可能只需注册.UIApplicationWillEnterForeground通知(完全绕过应用程序委托方法):

 class ViewController: UIViewController { private var notification: NSObjectProtocol? override func viewDidLoad() { super.viewDidLoad() notification = NotificationCenter.default.addObserver(forName: .UIApplicationWillEnterForeground, object: nil, queue: .main) { [unowned self] notification in // do whatever you want when the app is brought back to the foreground } } deinit { // make sure to remove the observer when this view controller is dismissed/deallocated if let notification = notification { NotificationCenter.default.removeObserver(notification) } } } 

请注意,在完成closures中,我包含了[unowned self]以避免强引用循环,如果您碰巧在块内部引用self ,则可以防止视图控制器被释放(如果您想要这样做,您大概需要这样做更新一个类variables或做几乎任何有趣的事情)。

或者,如果您不想使用基于块的通知,则可以使用旧的基于select器的方法:

 class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: .UIApplicationWillEnterForeground, object: nil) } func willEnterForeground(_ notification: NSNotification!) { // do whatever you want when the app is brought back to the foreground } deinit { // make sure to remove the observer when this view controller is dismissed/deallocated NotificationCenter.default.removeObserver(self) } } 

在Swift 3中,它取代并生成了以下内容。

  override func viewDidLoad() { super.viewDidLoad() foregroundNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillEnterForeground, object: nil, queue: OperationQueue.main) { [unowned self] notification in // do whatever you want when the app is brought back to the foreground }