0

I am currently working on this app that is integrated to a wordpress website. App Fetches JSON data and displays in TextView.

The am facing a problem with the HTML characters. The worpress website adds HTML codes such as and when its diplays in the app it doesnt decode.

Is there a way of decoding html charaters?

I am currently using below codes:

descTextView.text = NewsContentViewController.newsDetail.desc

enter image description here

Aslan Kayardi
  • 423
  • 1
  • 4
  • 12
  • Lets make it a bit clear: if you have a desc like: This text is: Some text do you want to have your result as "This text is:" or do you want it as "This text is: Some text"? – cenk ebret Jan 14 '20 at 12:36
  • I had the same issues with WP API and html tags. So, I added [SwiftSoup](https://github.com/scinfu/SwiftSoup) for converting html to correct (clear) text. – Vadim Nikolaev Jan 14 '20 at 12:53
  • Does this answer your question? [Swift: Display HTML data in a label or textView](https://stackoverflow.com/questions/37048759/swift-display-html-data-in-a-label-or-textview) – dahiya_boy Jan 14 '20 at 12:56

1 Answers1

1

Try using NSAttributedString like so,

let str = NewsContentViewController.newsDetail.desc

if let data = str.data(using: .utf8) {
    do {
        let attrStr = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
        descTextView.attributedText = attrStr
        print(attrStr)
    } catch {
        print(error)
    }
}

In the above code, do handle if NewsContentViewController.newsDetail.desc is optional String.

PGDev
  • 23,751
  • 6
  • 34
  • 88
  • `if let data = str.data(using: .utf8) {` string conversion to utf8 will never fail. You can force unwrap it safely. Note that since Swift 3 `Data` conforms to `RandomAccessCollection` and you can simply pass string utf8 view to its initializer which returns non optional. `let data = Data(str.utf8)` – Leo Dabus Jan 14 '20 at 14:38
  • @LeoDabus Noted. Thanks – PGDev Jan 14 '20 at 14:39
  • Error: Cannot assign value of type 'NSAttributedString' to type 'String?' – Aslan Kayardi Jan 14 '20 at 15:53
  • It works without error but this time it cant convert Turkish Characters – Aslan Kayardi Jan 14 '20 at 16:15
  • @AslanKayardi Great. Do accept if the answer worked. Happy coding.. – PGDev Jan 15 '20 at 05:55