Swift:如何检查字符串是否仅包含URL

时间:2018-07-06 10:43:59

标签: swift url

从服务器端来看,有时我会得到简单的字符串,有时会包含URL,有时仅包含URL。如何检查该字符串是否仅包含URL,而不包含其他文本。

enter image description here

1 个答案:

答案 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.
}

希望这对您有帮助