Home > Net >  Is it possible to open a markdown link in our app instead of Safari?
Is it possible to open a markdown link in our app instead of Safari?

Time:11-30

When you use markdown (example below) and you tap on links swift automatically closes my app and opens links in Safari but I'd like to open links in a webview inside my app, is it possible?

Text("Hello! Example of a markdown with a link [example](https://example.com)")

CodePudding user response:

The SwiftUI environment includes a URL handler which, by default, opens links in Safari, but you can provide your own handler to override this.

Text("Hello! Example of a markdown with a link [example](https://example.com)")
  .environment(\.openURL, OpenURLAction { url in
    // ... set state that will cause your web view to be loaded...
    return .handled
  })

The OpenURLAction has to return a value of type OpenURLAction.Result - here, .handled tells the system that you have dealt with the URL yourself so the OS doesn't have to do anything else.

You could also include certain logic such that if (for example) the URLs pointed to specific hosts, you handled them, but everything else should open in Safari; in that case, you'd return .handled for the URLs you're taking responsibility for, and .systemAction for any URL where the default behaviour should be used.

Other return types include .discarded to tell the app to ignore the tap on the link, and a version of .systemAction that allows you to redefine the link that opens in Safari. I don't think either fit your use case here, though.

This post on fivestars.blog goes into more detail. Also check out the openURL and OpenURLAction documentation.

  • Related