【问题标题】:handling external links in swift UIWebKit?在 swift UIWebKit 中处理外部链接?
【发布时间】:2018-08-25 18:48:51
【问题描述】:

我正在使用 swift 4 开发网络视图。 我正在加载本地 html 文件,这些页面中有一些指向其他网站的链接,但是一旦我点击其中任何一个,我想将它们加载到 safari 或默认浏览器而不是 WebView(浏览器)中。

我的 webView 被称为“浏览器”

这是我的 ViewController.swift 代码:

import UIKit
import WebKit

class ViewController: UIViewController {

@IBOutlet weak var browser: WKWebView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    let htmlpath = Bundle.main.path(forResource: "kusrc/index", ofType: "html")
    let url = URL(fileURLWithPath: htmlpath!)
    let request = URLRequest(url: url)
    browser.load(request)


}

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





}

有人可以帮帮我吗? google 中的大部分结果都不是我需要的...

是否有可能制作一个 if 语句,询问字符串前缀是否为“http:// 或 https://”,然后打开 safari,否则为“浏览器”

【问题讨论】:

    标签: ios swift uiwebview webkit


    【解决方案1】:

    我想你正在寻找这个委托方法:

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            guard let url = navigationAction.request.url else {
                decisionHandler(.allow)
    
                return
            }
    
            UIApplication.shared.open(url)
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
    

    如果您想根据URL 方案进行区分,可以使用URLComponents 将URL 拆分为各个部分。

    let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
    if components?.scheme == "http" || components?.scheme == "https" {
        // insert your code here
    }
    

    // 编辑(稍微详细一点):

    1. 将WebKit 导入您班级的最顶端:import WebKit
    2. 通过在父类后面添加WKNavigationDelegate 使您的类符合WKNavigationDelegate:class ViewController: UIViewController, WKNavigationDelegate
    3. 将您的类分配给 WKWebView 的导航委托:browser.navigationDelegate = self
    4. 将上述代码添加到您的课程中

    你的课程最终应该是什么样子的要点:WKWebView open links in Safari

    这里有一个关于这个主题的非常好的教程:https://www.hackingwithswift.com/example-code/wkwebview/how-to-control-the-sites-a-wkwebview-can-visit-using-wknavigationdelegate

    【讨论】:

    • 老实说,我实际上正在开发安卓应用程序,这是我第一次在 swift 上进行开发。抱歉这个愚蠢的问题,但我应该在哪里添加所有这些?
    • 你能解释一下究竟是什么不起作用,也许可以分享你正在处理的网址吗?
    • 可能太早了;)再试一次,我还在编辑文件。
    • 我正在尝试打开一个网页 play.google.com/store/apps/…,但它仍然在 webview 中打开它,而不是在 safari 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多