NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

SOLVED: Text formatting

Forums > SwiftUI

I'm getting back from text from an api call.

The text returned has embedded codes like this





At present I'm just displaying what is returned using a text command, but that looks rubbish.

Is there a way to automatically reformat this type of text?

   

There's no real built-in way to do it. You can convert HTML entities to their equivalent using an extension like this:

import UIKit

extension String {
    var decoded: String {
        let attr = try? NSAttributedString(data: Data(utf8), options: [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ], documentAttributes: nil)

        return attr?.string ?? self
    }
}

let text = "It&#39s a party!"
print(text.decoded)
//result == It's a party!

But the problem with your specific example is that 
 is ASCII 10, i.e., a newline, which is whitespace that is ignored by HTML.

So input like One

Two comes out as One Two rather than the expected result.

If the only entity you are dealing with is &#10; then I guess you could just replace them with \n in your string before you display it. Or you could replace &#10; with <br> in your string before using the above extension to convert it. <br> is HTML that can be transformed by NSAttributedString.

   

Thanks for your help. I've been investigating some of the other replies from calling the API. Looks like these are as you say HTML formatting commands that have been left in the JSON. There is also an API call to get the data in XML format, which I might try instead, but as you say I could just try a few Replace commands to strip out the HTML formatting.

   

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.