UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

1      

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

1      

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

1      

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?

1      

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.

1      

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.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.