0

While parsing I use this code

  func encode() -> String{
        var newStr = String(utf8String: self.cString(using: .utf8)!)
        newStr = newStr!.removingPercentEncoding

        guard let data = String(utf8String: self.cString(using: .utf8)!)?.data(using: .utf8) else {
            return newStr!
        }     
        guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding:  String.Encoding.utf8.rawValue], documentAttributes: nil) else {
            return newStr!
        }
       return  attributedString.string
    }

the problem is that it removes the \n. So I do not display the text correctly

3
  • TBH, you are doing very strange things with cString there. It's hard to just look at the code. Can you please at least debug it and find after which line the newline is lost? Commented Aug 21, 2018 at 11:11
  • Not related but the double String round-trip is horrible. Converting to cString and back to String is nonsense. Replace the first two lines and the entire first guard statement with let data = Data(self.utf8) and replace return newStr! with return self Commented Aug 21, 2018 at 11:14
  • 1
    Can you tell us what you are trying to accomplish? then it might be easier to help you Commented Aug 21, 2018 at 11:30

1 Answer 1

1

That's because you are using NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html

depending on what you are trying to accomplish, you may just ignore that fact or replace "\n" with something else in your String.

Sign up to request clarification or add additional context in comments.

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.