如何从 appdelegate.swift 控制 uiwebview

How to control uiwebview from appdelegate.swift

我正在尝试通过 AppDelegate.swift 控制 ViewController 的 UIWebView,例如当应用程序在后台发送时显示页面。

但我似乎无法从 AppDelegate 控制 UIWebView。 (没有发生编译错误。但简单地说,UIWebView 在下面的示例中没有显示 bar.html。) 如何从 AppDelegate(或不同的视图)控制 UIWebView?

示例如下。

AppDelegate:

func applicationDidEnterBackground(application: UIApplication) {
    let viewController: ViewController = ViewController()
    var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bar", ofType: ".html")!)!
    var request = NSURLRequest(URL: url)
    ViewController().webView.loadRequest(request)
}

ViewController.swift

class ViewController: UIViewController, UIWebViewDelegate{
    var webView: UIWebView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.webView = UIWebView(frame: CGRectMake(0, UIApplication.sharedApplication().statusBarFrame.height, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
        self.webView.delegate = self
        var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("foo", ofType: ".html")!)!
        var request = NSURLRequest(URL: url)
        self.webView.loadRequest(request)
        self.view.addSubview(self.webView)
    }
}

好的,我发现使用本地通知来解决这个问题。

我把代码改成这样:

AppDelegate.swift:

NSNotificationCenter.defaultCenter().postNotificationName("applicationWillResignActive", object: nil)

将此行添加到 ViewController.swift 中的 "viewDidLoad" 函数中:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "funcNameToFire:", name:"applicationWillResignActive", object: nil)

并将此函数添加到 ViewController.swift:

的某处
    func funcNameToFire(notification: NSNotification){      
        let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bar", ofType: ".html")!)!
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }