【问题标题】:How To Pass Different URLs in WkWebView in IOS?IOS中如何在WkWebView中传递不同的URL?
【发布时间】:2020-09-02 10:35:46
【问题描述】:

我想在同一个 WkWebView 控制器上调用“隐私政策”和“用户条款”网络链接。我在初始视图控制器中定义了两个不同的按钮,当它们中的任何一个被按下时,我在变量中分配了相关的 URL 字符串。然后我通过执行 segue 将它传递给 WkWebView 控制器。请参阅下面的两个控制器。我的问题是在第一次运行时,URL 返回 nil,因为当我按下按钮时,它会跳转到 WkWebView 控制器并崩溃。如果我在初始化时分配一个默认链接,它会按预期工作。我不明白为什么它在第一次运行时不进行 URL 分配行。非常感谢任何帮助,因为我还找不到任何解决方案。 (苹果链接只是例子)

分配 URL 并执行 segues 的初始控制器:

class InfoViewController: UIViewController {

var myURL: String?

@IBAction func helpButton(_ sender: UIButton) {
}


@IBAction func privacyPolicyButton(_ sender: UIButton) {
          
    
    myURL =  "https://www.apple.com/legal/intellectual-property/piracy.html"
    

    performSegue(withIdentifier: "GoToWebView", sender: self)

}

@IBAction func termsOfUseButtton(_ sender: UIButton) {
    
     myURL = "https://www.apple.com/legal/internet-services/terms/site.html"

     performSegue(withIdentifier: "GoToWebView", sender: self)
}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      super.prepare(for: segue, sender: sender)
             if segue.identifier == "GoToWebView" {
                 let destinationVC = segue.destination as! WebViewController

                destinationVC.url = myURL

             }
         }

我的第二个控制器 (WkWebView) 用于查看 Apple 文档中描述的网络链接:

class WebViewController: UIViewController, WKUIDelegate {

var webView: WKWebView!

var url: String?

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView
}
override func viewDidLoad() {
    super.viewDidLoad()

    let myRequest = URLRequest(url: URL(string: url!)!)
    webView.load(myRequest)
}

}

【问题讨论】:

    标签: ios segue wkwebview


    【解决方案1】:

    你应该在设置url后重新加载你的webView

    class WebViewController: UIViewController, WKUIDelegate {
    
        var url: String? {
            didSet(oldValue) {
                if self.isViewLoaded {
                    let myRequest = URLRequest(url: URL(string: url!)!)
                    webView.load(myRequest)
                }
            }
        }
    
        ...
    }
    

    【讨论】:

    • 嗨,尤金,不幸的是,它不起作用。 self.isViewLoaded 从未执行。它不会崩溃,只是出现空白屏幕。
    【解决方案2】:

    我终于在代码中发现了我的错误。我错误地控制将segue从初始控制器上的操作按钮拖动到第二个控制器,这导致每当按下按钮时运行“准备segue”方法,而不处理下一行以分配IBaction func下的URL。我更正了创建从控制器到控制器的 segue,它工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 2018-01-18
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多