gonzalezreal / swift-markdown-ui

Display and customize Markdown text in SwiftUI
MIT License
2.26k stars 267 forks source link

How to open a link in app (question) #66

Closed abhinavtatch closed 2 years ago

abhinavtatch commented 2 years ago

Right now, the default implementation is to open a browser on the phone, how can one change this to open an in app browser ?

Any help appreciated. Thank you

bigadz commented 2 years ago

If using SwiftUI, place this on the view of your choice, probably your top level view, which is likely called ContentView:

        .onOpenURL(perform: { url in
            print("ContentView Top level url: \(url)")
        })
abhinavtatch commented 2 years ago

Thank you @bigadz , unfortunately I'm using UIKit

bigadz commented 2 years ago

@abhinavtatch so now I'm guessing: Perhaps you can handle this via the UIAppDelegate? See https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623112-application

abhinavtatch commented 2 years ago

@bigadz , sorry, my question wasn't clear, I'm using the markdown UI package, and when there is a a link in the attributed string of the DefaultMarkdownStyle() , On tap of this markdown link, I want the app to open the link in the in app browser ( i have WKWebView in a VC already ) rather than opening un Safari or the default browser on the phone.

Apologies for the tardy question before

gonzalezreal commented 2 years ago

Hi @abhinavtatch, MarkdownUI 1.0.0 now provides custom link handling. You will find a couple of examples in the README and the documentation.

ebsi-ffoster commented 4 months ago

I'm still trying to wrap my head around this and having the same issue, here is my code:

extension Theme {
    static let customTheme = Theme()

    // other config code...

        .link {
            ForegroundColor(Color(uiColor: Petram.config.theme.secondaryColor))
        }
}

// ContentView where the Markdown is shown...

VStack {
          Markdown(viewModel.markdown)
                .markdownTheme(.customTheme)
}

How do I ensure links are open in-browser as opposed to externally? What am I missing? The documentation is a little lacking as far as I could find. Any help is appreciated!

gonzalezreal commented 4 months ago

Hi @ebsi-ffoster,

To customize how your app handles URLs, you must use SwiftUI's OpenURLAction.

The system provides a default open URL action with behavior that depends on the contents of the URL. You can set a custom action using the environment(::) view modifier. Any views that read the action from the environment, including the built-in Link and Text, or Markdown, use your action.

You can see this in action in the Demo project, where a custom URL action is extracting the URL fragment and scrolling to the appropriate heading, instead of opening the URL in Safari:

https://github.com/gonzalezreal/swift-markdown-ui/blob/ae799d015a5374708f7b4c85f3294c05f2a564e2/Examples/Demo/Demo/RepositoryReadmeView.swift#L127