Advertisement
Guest User

Untitled

a guest
Nov 12th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.97 KB | None | 0 0
  1.         let initialText = "<p>FirstParagraph1\nFirstParagraph2</p> Rest"
  2.         print("Taget:\n\(initialText)")
  3.  
  4.         let attributedString = try! NSMutableAttributedString.init(data: initialText.data(using: .utf8)!,
  5.                                                                    options: [NSAttributedString.DocumentReadingOptionKey.documentType : NSAttributedString.DocumentType.html],
  6.                                                                    documentAttributes: nil)
  7.         print("attributedString:\n\(attributedString)")
  8.  
  9.         let initialHTMLRenderingData = try! attributedString.data(from: NSRange(location: 0, length: attributedString.length),
  10.                                                                   documentAttributes: [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html])
  11.         let defaultHTMLString = String(data: initialHTMLRenderingData, encoding: .utf8)
  12.         print("defaultHTMLString:\n\(defaultHTMLString)")
  13.  
  14.  
  15.         attributedString.enumerateAttribute(NSAttributedStringKey.paragraphStyle,
  16.                                             in: NSRange(location: 0, length: attributedString.length),
  17.                                             options: []) { (paragraph, range, pointee) in
  18.                                                 if (paragraph as? NSParagraphStyle) != nil {
  19.                                                     let occurence = attributedString.attributedSubstring(from: range).string
  20.                                                     let replacement = "<p>" + occurence + "</p>"
  21.                                                     attributedString.replaceCharacters(in: range, with: replacement)
  22.                                                 }
  23.         }
  24.         print("attributedString.string:\n\(attributedString.string)")
  25.  
  26.         let withBreakLines = attributedString.string.replacingOccurrences(of: "\n", with: "<\\br>")
  27.  
  28.         print("withBreakLines:\n\(withBreakLines)")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement