[英]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.