0

Edit: Reed the ffing description before downvoting!

I have been trying to find a solution for days. I found several posts here on stackoverflow but none of them that handle a similiar solution. In receive a description text for an object from the backend in html like this:

"My two favorite places to indulge on my sugar cravings are <a 
href=\"https://huizevanwely.nl/\">Huize van Wely</a> (located in the 
Gelderlandplein shopping mall and Beethovenstraat) and <a 
href=\"http://linnick.nl/\">Linnick</a>. The first is one I ........."

I would like to find a way to detect the links and only show the link text ánd have the link text clickable.

I have this method that sucessfully strips the links:

func stripLinks(text: String) -> String {
    let pattern = "<a href=\"[^\"]+\">([^<]+)</a>"
    do {
        let regex = try NSRegularExpression(pattern: pattern,
                                            options: [])
        let stripped = regex.stringByReplacingMatches(in: text,
                                                      options: [],
                                                      range: NSRange(location: 0, length: text.count),
                                                      withTemplate: "$1")
        return stripped
    } catch {
        print("WARNING: regex failed")
        return text
    }
}

But this way the textView does not detect the links anymore, so i have the plain text but you can't click the text to go to the website.

Can anyone help with an approach that would work, please. I think that i should use an attributed string to get this working but i have failed in trying to implement it.

Thanks in advance.

FredFlinstone
  • 896
  • 11
  • 16
  • Why don't you just parse the contents as HTML: https://stackoverflow.com/questions/37048759/swift-display-html-data-in-a-label-or-textview – Scriptable Jun 18 '18 at 14:22
  • Great suggestion. I’ll try it and i’ll get back here. Thx – FredFlinstone Jun 18 '18 at 14:42
  • use this, https://stackoverflow.com/questions/26962530/hyperlinks-in-a-uitextview – Aju Antony Jun 18 '18 at 15:20
  • @Scriptable the suggestion in the link works. I was using the string in stead of the attr.string. The only thing now is that the parsed text contains this character: Â at several places. Any idea what is causing that. And again thanks for the link – FredFlinstone Jun 18 '18 at 16:33
  • Ok, so i found the solution. The encoding was using utf8, changing it to utf16 solved it. @Scriptable if you can put it in answer, i'll accept it. – FredFlinstone Jun 18 '18 at 16:46
  • Probably best to mark as a duplicate if the other answer solved it for you, i'll suggest and you can approve if you like – Scriptable Jun 18 '18 at 17:05
  • Well, that's not the correct link to what helped me. It was the first link: https://stackoverflow.com/questions/37048759/swift-display-html-data-in-a-label-or-textview. – FredFlinstone Jun 19 '18 at 05:30

0 Answers0