Open WebView URL in Browser

后端 未结 2 1141
傲寒
傲寒 2021-01-15 01:54

I made a very simple Swift application that loads a webpage with links on it. Whenever I click the links, they do not open. How would I got about having the links on the loa

2条回答
  •  一向
    一向 (楼主)
    2021-01-15 02:23

    First, set your WebView's policy delegate and your initial URL as a class variable:

    let url = NSURL(string: "http://www.google.com/")!
    
    // ...
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Do any additional setup after loading the view.
    
        self.webView.policyDelegate = self
    
        self.webView.mainFrame.loadRequest(NSURLRequest(URL: self.url))
    }
    

    Then, override the delegate methods to intercept navigation.

    override func webView(webView: WebView!, decidePolicyForNewWindowAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, newFrameName frameName: String!, decisionListener listener: WebPolicyDecisionListener!) {
        println(__LINE__) // the method is needed, the println is for debugging
    }
    
    
    override func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
        if request.URL!.absoluteString == self.url.absoluteString { // load the initial page
            listener.use() // load the page in the app
        } else { // all other links
            NSWorkspace.sharedWorkspace().openURL(request.URL!) // take the user out of the app and into their default browser
        }
    }
    

提交回复
热议问题