NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How do I open links within WKWebView in Safari Browser or sheet?

Forums > SwiftUI

In my app, I need to display some HTML string content so I created a UIViewRepresentable like below:

import SwiftUI
import WebKit

struct HTMLStringView: UIViewRepresentable {
    let htmlContent: String

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }

}

and I display it in my view like so:

HTMLStringView(htmlContent: "HTML String")

The problem is that some of the HTML content have links and they open within the view. How can I open the links in Safari Browser or at least a sheet instead? Any help will be appreciated. I am very much new ro Swiftui. Thank you.

   

You can add this Link( )

struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            Image(systemName: "swift")
                .imageScale(.large)
                .foregroundColor(.accentColor)

            Link("Learn SwiftUI", destination: URL(string: "https://www.hackingwithswift.com/quick-start/swiftui")!)
        }
        .padding()
    }
}

Check out this article How to open web links in Safari

   

Thank you for the reply. The question isnt about how to open links.

   

That is exactly your question.

The problem is that some of the HTML content have links and they open within the view. How can I open the links in Safari Browser or at least a sheet instead?

   

Sir, I made it clear that

"I need to display some HTML string content"

that is why I created "HTMLStringView" that conforms to a "UIViewRepresentable" of the type "WKWebView".

I also stated clearly that my problem is:

The problem is that some of the HTML content have links and they open within the view. How can I open the links in Safari Browser or at least a sheet instead?

The problem is so clear. If I want to open a link, I would use Link(). If you read thruough you will discover that my problem isn't about opening links sir. Thank you.

   

For anyone having the same problem, here is how I was able to solve it eventually:

First of all I created a URL extension to test if the URL is reachable. This part is optional. I needed it so that users are not taken away from my app if indeed the URL leads nowhere:

extension URL {
    func isReachable(completion: @escaping (Bool) -> ()) {
        var request = URLRequest(url: self)
        request.httpMethod = "HEAD"
        URLSession.shared.dataTask(with: request) { _, response, _ in
            completion((response as? HTTPURLResponse)?.statusCode == 200)
        }.resume()
    }
}

Then I created a Coordinator class to serve as the WKNavigationDelegate:

class Coordinator : NSObject, WKNavigationDelegate {
        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            guard let url = navigationAction.request.url else {
                decisionHandler(.allow)
                return
            }

            if url.absoluteString.contains("www.youtube.com"){ //In my case I needed to allow links with Youtube
                decisionHandler(.allow)
            } else {
                url.isReachable { success in //To test if the URL is reachable
                    if success {
                        decisionHandler(.cancel)
                        DispatchQueue.main.async { //Needs to run on the main thread to prevent UI issues
                            UIApplication.shared.open(url)
                        }
                    } else {
                        decisionHandler(.allow)
                    }
                }
            }
        }
    }

I added the following line to my struct to make it aware of the Coordinator:

func makeCoordinator() -> Coordinator { 
        Coordinator()
    }

Finally, I assign the coordinator as the view's navigation delegate

func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.navigationDelegate = context.coordinator //Assign the coordinator as the view's navigation delegate
        uiView.loadHTMLString(htmlContent, baseURL: nil)
    }

And my links within the HTML String now open inside Safari instead of in my app.

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.