如何从appdelegate.swift控制uiwebview

时间:2015-03-20 16:23:41

标签: ios iphone swift uiwebview appdelegate

我正在尝试从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)
    }
}

1 个答案:

答案 0 :(得分:0)

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

我改变了代码是这样的:

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)
    }