0

Hello I have a string that I want to write to a text document in Swift. Because the text document has line breaks, however, the string seems to be in HTML format. Here is what I want to do:

    //Covert str1 to str2
    var str1 = "1<div>2</div><div>3</div><div>4</div>"
    var str2 = "1        
                2
                3
                4" //Text document will have text that looks like this (With line breaks)

2 Answers 2

1

You can try with NSAttributedString:

let htmlString = "1<div>2</div><div>3</div><div>4</div>"
NSAttributedString(data: htmlString.dataUsingEncoding(NSUnicodeStringEncoding)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil); 

this will produce:

"1\n2\n3\n4\n"
Sign up to request clarification or add additional context in comments.

3 Comments

If this is always NSAttributedString, how do write that to a text file?
NSAttributedString has property string
from documentation: Attachment characters are not removed from the value of this property
1

Swift 3.0: You can pop this directly into Xcode's playground to check it out.

let htmlString = "1<div>2</div><div>3</div><div>4</div>"
func getHtmlFormat(fromString htmlString: String) -> NSAttributedString? {
    guard let htmlData = htmlString.data(using: String.Encoding.unicode) else
    {
        print("Could not get htmlData")
        return nil
    }
    do {
        return try NSAttributedString(data: htmlData, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    } catch let error {
        print(error)
        return nil
    }
}

let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
textView.attributedText = getHtmlFormat(fromString: htmlString)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.