Created
December 31, 2018 00:23
-
-
Save ealeksandrov/65e602d792f9f466329ace6b75f56284 to your computer and use it in GitHub Desktop.
Extension to convert markdown String to NSAttributedString with links ready to use in UITextView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// String+MarkdownLinks.swift | |
// | |
// Copyright © 2018 Evgeny Aleksandrov. MIT License. | |
import Foundation | |
extension String { | |
func parseMarkdownLinks() -> NSMutableAttributedString { | |
let pattern = "\\[([^\\]]+)\\]\\(([^\\)\"\\s]+)(?:\\s+\"(.*)\")?\\)" | |
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { return NSMutableAttributedString(string: self) } | |
let attributedText = NSMutableAttributedString(string: self) | |
let numberOfLinksFound = regex.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: self.count)) | |
for _ in 0..<numberOfLinksFound { | |
let textToParse = attributedText.string | |
if let match = regex.firstMatch(in: textToParse, options: [], range: NSRange(location: 0, length: textToParse.count)), match.numberOfRanges > 2 { | |
let matchRange = match.range | |
let linkRange = match.range(at: 1) | |
let urlRange = match.range(at: 2) | |
let linkAttributedStr = NSAttributedString(string: (textToParse as NSString).substring(with: linkRange), attributes: [NSAttributedString.Key.link: (textToParse as NSString).substring(with: urlRange)]) | |
attributedText.replaceCharacters(in: matchRange, with: linkAttributedStr) | |
} | |
} | |
return attributedText | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment