Our app Api returns a field with custom format for user mentions just like: "this is a text with mention for @(steve|user_id)". So before display it on UITextView, need to process the text, find the pattern and replace with something more user friendly. Final result would be "this is a text with mention for @steve" where @steve should have a link attribute with user_id. Basically the same functionality as Facebook.
First I've created an UITextView extension, with a match function for the regex pattern.
extension UITextView {
func processText(pattern: String) {
let inString = self.text
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSMakeRange(0, inString.characters.count)
let matches = (regex?.matchesInString(inString, options: [], range: range))! as [NSTextCheckingResult]
let attrString = NSMutableAttributedString(string: inString, attributes:attrs)
//Iterate over regex matches
for match in matches {
//Properly print match range
print(match.range)
//A basic idea to add a link attribute on regex match range
attrString.addAttribute(NSLinkAttributeName, value: "\(schemeMap["@"]):\(must_be_user_id)", range: match.range)
//Still text it's in format @(steve|user_id) how could replace it by @steve keeping the link attribute ?
}
}
}
//To use it
let regex = ""\\@\\(([\\w\\s?]*)\\|([a-zA-Z0-9]{24})\\)""
myTextView.processText(regex)
This is what I have right now, but I'm stucked trying to get final result
Thanks a lot !