Skip to content

Instantly share code, notes, and snippets.

@AmitaiB
Last active April 23, 2019 10:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmitaiB/7833ba4285d8b8be4abcb31b97539737 to your computer and use it in GitHub Desktop.
Save AmitaiB/7833ba4285d8b8be4abcb31b97539737 to your computer and use it in GitHub Desktop.
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

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