![](/img/trans.png)
[英]How to do routing from AppDelegate.swift to any View controller
[英]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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.