我正在学习OS X / Swift开发并加载了一个网页,其中包含指向其他网站的链接,我如何在默认浏览器中打开这些链接。在点击链接时,根本没有任何事情发生。这是我的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.
}
}
}
答案 0 :(得分:1)
我不清楚你在问什么。
我想你问如何在桌面浏览器(例如Safari)中打开WebView中点击链接?
如果这是您要实现的目标,则可以使用WebPolicyDelegate来确定网址的打开位置。
例如
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)
}
}
}
}
如果这不是您要求的,请编辑您的问题以使其更清晰。