¿Hay alguna forma actualizada de convertir enlaces dentro del texto? Recibo este tipo de texto de una API:
var someText: String = "with banks (for example to the sometimes controversial but leading exchange <a href="https://www.coingecko.com/en/exchanges/bitfinex">Bitfinex</a>)."¿Cómo puedo convertir ese enlace interno en un enlace en el que se puede hacer clic con el nombre correcto, en el ejemplo anterior: Bitfinex?
El texto podría contener varios enlaces. SwiftUI ahora admite Markdown, manualmente podría hacerlo así:
Text("[Privacy Policy](https://example.com)")pero, ¿cómo lo hago para un texto recibido de api con múltiples enlaces?
Buscando una solución Swift 5 y SwiftUI 3.
Lo que tienes es una cadena html. Puede interpretar su cadena html usando las opciones de inicialización de NSAttributedString NSAttributedString.DocumentType.html e inicializar una nueva AttributedString con ella. No es necesario manipular y/o analizar manualmente su cadena:
Primero agregue esta extensión a su proyecto:
extension StringProtocol { func htmlToAttributedString() throws -> AttributedString { try .init( .init( data: .init(utf8), options: [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil ) ) } } Luego extienda Text para agregar un inicializador personalizado:
extension Text { init(html: String, alert: String? = nil) { do { try self.init(html.htmlToAttributedString()) } catch { self.init(alert ?? error.localizedDescription) } } } import SwiftUI struct ContentView: View { var html = #"with banks (for example to the sometimes controversial but leading exchange <a href="https://www.coingecko.com/en/exchanges/bitfinex">Bitfinex</a>. For more info <a href="https://www.google.com/">Google</a>).""# var body: some View { Text(html: html) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }