【问题标题】:Accessing webView from another class Swift 3从另一个类 Swift 3 访问 webView
【发布时间】:2017-02-12 20:17:54
【问题描述】:

我有一个标签栏控制器,它有两个不同的视图控制器——每个控制器中都有一个 WKWebView。

这是在我的WebViewController里面:(如果我需要把ID扔给另一个webView的话,我基本上可以根据URL破译。

HTMLSermonAudioController().webView.load(URLRequest(url: url))

是我试图访问其他类的 webView 以更改已加载页面的 URL 的部分。

if requestURL.absoluteString.hasPrefix("bocaudio://?url="){
let url = URL(string: "https://storage.googleapis.com/boc-audio/123.mp3")!
HTMLSermonAudioController().webView.load(URLRequest(url: url))
tabBarController?.selectedIndex = 3
}

我也尝试过在 HTMLSermonAudioController 和其他各种方法中使用类函数,但我似乎无法访问

import UIKit
import WebKit

class HTMLSermonAudioController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
    webView = WKWebView()
    webView.navigationDelegate = self
    view = webView
    let url = URL(string: "https://www.boc.domain/audioapp/290/")!
    webView.load(URLRequest(url: url))
    webView.allowsBackForwardNavigationGestures = true
}


class func test(){
    let url = URL(string: "https://www.boc.domain/audioapp/290/")!
    HTMLSermonAudioController().webView.load(URLRequest(url: url))
}


func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    title = webView.title
}

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    decisionHandler(.allow)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

因为 webView 在 override func loadView 中,我很难访问它。感谢上帝提供了混合应用程序,因为一旦我克服了这最后一道障碍,我就不必担心更多的 swift 代码了。

【问题讨论】:

    标签: ios iphone swift wkwebview


    【解决方案1】:

    我最终弄清楚了如何使用 NotificationCenter 来做到这一点

    NotificationCenter.default.addObserver(self, selector: #selector(HTMLSermonAudioController.connectWithSpecifiedItem), name: urlNotification, object: nil)
    
    
    func connectWithSpecifiedItem(notification: NSNotification){
        let itemUrl = notification.object as! NSURL
    
        //webView.load(URLRequest(url: url))
        self.webView!.load(URLRequest(url: itemUrl as URL))
    }
    

    在其他控制器中:

    if requestURL.absoluteString.hasPrefix("https://www.place.domain/audioapp/"){
            tabBarController?.selectedIndex = 3
            sendData(url: requestURL)
            decisionHandler(.cancel)
            return
        }
    func sendData(url: URL){
            NotificationCenter.default.post(name: HTMLSermonAudioController().urlNotification, object: requestURL)
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2017-07-30
      • 2016-03-19
      • 1970-01-01
      • 2020-11-04
      相关资源
      最近更新 更多