V
V
Vadim2021-01-29 16:20:32
iOS
Vadim, 2021-01-29 16:20:32

How to open a link to an external site in an application in a browser?

There is such an application that opens a specific site example.com. And everything seems to be ok, it opens as it should, but if a link to an external site appears, then clicking on it doesn’t work

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!
    

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let hey =  "https://example.com"
        
        webView.load(URLRequest(url: URL(string: hey)!))
        // Do any additional setup after loading the view, typically from a nib.
    }


}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NSA-bot, 2021-01-29
@zomik

You need to add a protocol, specify its delegate, and add a method. I marked with comments the places where I added all this to your code.

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {  // Здесь протокол WKUIDelegate
  
  @IBOutlet weak var webView: WKWebView!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    self.webView?.uiDelegate = self // Делегат
    
    let hey = "https://example.com"
    
    webView.load(URLRequest(url: URL(string: hey)!))
  }
  
  // И этот метод
  func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if navigationAction.targetFrame == nil {
      webView.load(navigationAction.request)
    }
    return nil
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question