【问题标题】:How to control uiwebview from appdelegate.swift如何从 appdelegate.swift 控制 uiwebview
【发布时间】:2015-03-20 16:23:40
【问题描述】:

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

【问题讨论】:

    标签: ios iphone swift uiwebview appdelegate


    【解决方案1】:

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

    我改的代码是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多