使用Swift 4,我试图检测字符串中的url。我目前正在使用此代码:
let urlLink : String = "https://skift.com/2017/11/27/8-financial-themes-shaping-the-hotel-industry-in-2018-and-beyond/?utm_campaign=Early%20Time%20Zone%20-%20Skift%20Daily%20Newsletter&utm_source=hs_email&utm_medium=email&utm_content=58793637&_hsenc=p2ANqtz-8cG4tZKNEv7E1FRrVn-T-qwKRpJKx8JQBAgF7priRL78ToAX49w4e1R2sdCxSI9lik4NXXkW241XSN3UkVxVrjVjRu7x0N8i-txn8F0Jxnhgej3OI&_hsmi=58793637"
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: urlLink, options: [], range: NSRange(location: 0, length: urlLink.count))
正如您所看到的,我的字符串已经过格式化,可以用"%20" 替换空格。
问题是我的代码在最后一行崩溃了。有没有更好的方法来格式化我的字符串?
我找到了一种解决方法,将"%20" 替换为"" ,这工作正常,但我我相信有更好的方法来处理它。
答案 0 :(得分:0)
检查一下
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: input!, options: [], range: NSMakeRange(0, (input?.characters.count)!))
var url = String()
for match in matches
{
url = (input! as NSString).substring(with: match.range)
}