UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

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.

2      

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.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.