Swift 如何在WebView的默认浏览器中打开链接

Swift 如何在WebView的默认浏览器中打开链接,swift,macos,cocoa,webview,Swift,Macos,Cocoa,Webview,我正在学习OS X/Swift development,已经加载了一个包含其他网站链接的网页,以及如何在默认浏览器中打开这些链接。在点击链接的那一刻,什么都没有发生。这是我的ViewController.swift内容: import Cocoa import WebKit import Foundation class ViewController: NSViewController, WebFrameLoadDelegate, WKNavigationDelegate { @IB

我正在学习OS X/Swift development,已经加载了一个包含其他网站链接的网页,以及如何在默认浏览器中打开这些链接。在点击链接的那一刻,什么都没有发生。这是我的ViewController.swift内容:

import Cocoa
import WebKit
import Foundation

class ViewController: NSViewController, WebFrameLoadDelegate, WKNavigationDelegate {

    @IBOutlet weak var webView: WebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let URL = "https://test.mywebsite.com"

        self.webView.frameLoadDelegate = self
        self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: URL)!))



    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

我不完全清楚你在问什么

我想你是在问如何在桌面浏览器(如Safari)中打开在WebView中单击的链接

如果您正试图实现这一点,则可以使用来确定URL应在何处打开

例如


如果这不是您要问的问题,请编辑您的问题以使其更清楚。

使用,这是我要问的问题。使用此代码会使链接在运行应用程序时立即打开,而不会等到用户单击链接。我运行应用程序并自动打开链接。我只是用我提供的代码再次尝试,它似乎工作正常。使用故事板创建了一个新的Cocoa应用程序。在Interface Builder中将单个WebView添加到情节提要中。将上述代码粘贴到ViewController代码的上方。将WebView链接到ViewController。运行应用程序。当在WebView中单击链接时,它仅显示浏览器中的页面。你能在某个地方提供你的实际代码吗?我会仔细查看,看看为什么你会得到不同的结果。重复?
import Cocoa
import WebKit

class ViewController: NSViewController, WebFrameLoadDelegate, WebPolicyDelegate {

    @IBOutlet weak var webView: WebView!

    let defaultURL = "http://www.apple.com/"  // note we need the trailing '/' to match with our 'absoluteString' later

    override func viewDidLoad() {
        super.viewDidLoad()

        self.webView.frameLoadDelegate = self
        self.webView.policyDelegate = self
        self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: defaultURL)!))

    }

    func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {

        if let currentURL = request.URL {
            if currentURL.absoluteString == defaultURL {
                print("our base/default URL is being called - showing in WebView")
                listener.use()   // tell the listener to show the request
            } else {
                print("some other URL - ie. a link has been clicked - ignore in WebView")
                listener.ignore()   // tell the listener to ignore the request
                print("redirecting url: \(currentURL.absoluteString) to standard browser")
                NSWorkspace.sharedWorkspace().openURL(currentURL)
            }
        }
    }

}