NSAttributedString+Sweeter.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. //
  2. // NSAttributedString+Sweeter.swift
  3. //
  4. // Created by Yonat Sharon on 2019-02-08.
  5. //
  6. import Foundation
  7. public extension NSAttributedString {
  8. /// Sweeter: Create attributed string from HTML
  9. convenience init?(htmlString: String, defaultAttributes: [NSAttributedString.Key: Any]? = nil) {
  10. guard let data = htmlString.data(using: .utf8) else { return nil }
  11. let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
  12. .documentType: NSAttributedString.DocumentType.html,
  13. .characterEncoding: String.Encoding.utf8.rawValue,
  14. .defaultAttributes: defaultAttributes ?? [:],
  15. ]
  16. try? self.init(data: data, options: options, documentAttributes: nil)
  17. }
  18. }
  19. public extension NSMutableAttributedString {
  20. /// Sweeter: Make part of the string into a link.
  21. ///
  22. /// - Parameters:
  23. /// - url: link address.
  24. /// - anchorText: substring to make into a link.
  25. func link(anchorText: String, url: String) {
  26. guard let urlObject = URL(string: url) else { return }
  27. let anchorRange = mutableString.range(of: anchorText, options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive])
  28. guard NSNotFound != anchorRange.location else { return }
  29. addAttribute(.link, value: urlObject, range: anchorRange)
  30. }
  31. }