I have a string that has a url and some text ! The text can be before the url or after the url. So how can I split the string in two and know which one is Text and which one is URL.
For example String 1 = " This is stack overflow https://stackoverflow.com/questions/ask" (text is before the url)
String 2 = "https://stackoverflow.com/questions/ask This is stack overflow" (text is after the url)
I found the solution.
func getAttributedText(_ text1:String,text2:String) -> NSAttributedString {
let attributedString1 = NSMutableAttributedString(string:"(text1)\n", attributes: nil)
let attributedString2 = NSMutableAttributedString(string:"(text2)\n", attributes:nil)
attributedString1.append(attributedString2)
return attributedString1 }
let originalString = "https://medium.com/@felicity.johnson.mail/how-to-split-a-string-swift-3-0-e9b757445064 checking new post"
do {
let types: NSTextCheckingResult.CheckingType = .link
let detector = try? NSDataDetector(types: types.rawValue)
let matches = detector?.matches(in: originalString, options: .reportCompletion, range: NSMakeRange(0, originalString.count))
var link:String!
if (matches != nil){
for match in matches! {
link = (match.url?.absoluteString)!
break;
}
}
let mutableAttributedString = NSMutableAttributedString(string: originalString, attributes: nil)
let attributedText = getAttributedText("DOJ watchdog finds no bias in launch of Trump-Russia probe, but uncovers ‘significant’ FBI errors", text2:"The Justice Department’s inspector general, in a long-awaited review concerning the origins of the Russia investigation \n")
let userContent : String = ""
// Get range of text to replace
if let range = mutableAttributedString.string.range(of: link){
let nsRange = NSRange(range, in: mutableAttributedString.string)
// Replace content in range with the new content
mutableAttributedString.replaceCharacters(in: nsRange, with: userContent)
}
let userTypedContent = mutableAttributedString.string.trimmingCharacters(in: .whitespaces)
let urlContent = attributedText.string.trimmingCharacters(in: .whitespaces)
UIlablel.text = urlContent + userTypedContent }