答案 0 :(得分:0)
在您的ViewContoller中添加以下两个功能
func getUrlStringFromString(text: String) - > String {
var tempStrArray = text.components(separatedBy: " ")
var urlString = ""
for i in 0 ..< tempStrArray.count {
if isValidUrl(str: "\(tempStrArray[i])") {
urlString = tempStrArray[i]
}
}
return urlString
}
func isValidUrl(str: String) -> Bool {
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
if let match = detector.firstMatch(in: str, options: [], range: NSRange(location: 0, length: str.endIndex.encodedOffset)) {
// it is a link, if the match covers the whole string
return match.range.length == str.endIndex.encodedOffset
} else {
return false
}
}
然后使用您的字符串调用getUrlStringFromString
let urlString = self.getStringFromSting(text: YOUR_STRING)
if urlString != "" {
//YOUR_STRING have url. and urlString contains URL
} else {
//YOUR_STRING doesn't have url.
}
希望这对您有帮助