首页 > 解决方案 > Swift:如何检查字符串是否仅包含 URL

问题描述

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

在此处输入图像描述

标签: swifturl

解决方案


将以下两个功能添加到您的 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.
}

希望对你有帮助


推荐阅读