Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Extends String to created NSAttributedStrings, and vice versa, for many encoding types, including HTML and RTF.
//
// NSAttributedString+HTML.swift
//
// Created by Amitai Blickstein on 6/22/16.
// Copyright © 2016 Amitai Blickstein, LLC. All rights reserved.
//
import UIKit
////////////////////////
// ⇒ NSAttributedString
////////////////////////
extension NSAttributedString {
/// Attempts to create an `NSAttributedString` from an encoded string of the specified type.
static func fromEncodedString(_ eString: String, ext: DocEXT) -> NSAttributedString? {
guard let data = eString.data(using: .utf8) else { return nil }
let docType = documentTypeDictionary(extension: ext)
let result = try? NSAttributedString(data: data,
options: docType,
documentAttributes: nil)
return result
}
/// Attempts to create an NSAttributedString from an encoded **html** string.
static func fromHTML(_ html: String) -> NSAttributedString? {
return NSAttributedString.fromEncodedString(html, ext: .html)
}
////////////////////////
// NSAttributedString ⇒ <html>String</html>
////////////////////////
///Attemps to convert the receiver into an *encoded* string, according to chosen doc type.
// For a scrubbed string, use the NSAttributedString method `string`.
func encodedString(ext: DocEXT) -> String? {
let docType = documentTypeDictionary(extension: ext)
guard let data = try? self.data(from: NSRangeFromString(self.string), documentAttributes: docType)
else { return nil }
return String.init(data: data, encoding: .utf8)
}
}
////////////////////////
// <html>String</html> ⇒ NSAttributedString
////////////////////////
extension String {
func attributedString(ext: DocEXT) -> NSAttributedString? {
guard let data = self.data(using: .utf8) else { return nil }
let result = try? NSAttributedString(data: data,
options: documentTypeDictionary(extension: ext),
documentAttributes: nil)
return result
}
}
// Helper(s)
fileprivate func documentTypeDictionary(extension ext: DocEXT) -> [String: Any] {
let documentTypeDictionary: [DocEXT: Any] = [
.rtfd: NSRTFDTextDocumentType,
.rtf : NSRTFTextDocumentType,
.htm : NSHTMLTextDocumentType,
.html: NSHTMLTextDocumentType,
.txt : NSPlainTextDocumentType
]
let docType = documentTypeDictionary[ext]
return [NSDocumentTypeDocumentAttribute: docType ?? NSPlainTextDocumentType]
}
enum DocEXT: String {
case rtfd
case rtf
case htm
case html
case txt
}
@TuralVeli
Copy link

TuralVeli commented Apr 23, 2019

this is extension dont work swift 4.2 or 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment