简体   繁体   中英

How to control uiwebview from appdelegate.swift

I'm trying to control ViewController's UIWebView from AppDelegate.swift something like to show a page when the App sent in the background.

But it seems that I can't control UIWebView from the AppDelegate. (No compile error occurs. But simply, UIWebView doesn't show bar.html in the example below.) How can I control UIWebView from AppDelegate (or different view)?

Here's the example.

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

Okay, I discovered to use local notification to solve this problem.

I changed the code is like this :

AppDelegate.swift:

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

added this line to the "viewDidLoad" func in ViewController.swift :

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

and added this function somewhere into the ViewController.swift:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM