How to check validity of URL in Swift?

后端 未结 22 1729
不知归路
不知归路 2020-11-29 02:05

Trying to make an app launch the default browser to a URL, but only if the URL entered is valid, otherwise it displays a message saying the URL is invalid.

How would

22条回答
  •  渐次进展
    2020-11-29 02:25

    extension String {    
        func isStringLink() -> Bool {
            let types: NSTextCheckingResult.CheckingType = [.link]
            let detector = try? NSDataDetector(types: types.rawValue)
            guard (detector != nil && self.characters.count > 0) else { return false }
            if detector!.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count)) > 0 {
                return true
            }
            return false
        }
    }
    
    //Usage
    let testURL: String = "http://www.google.com"
    if testURL.isStringLink() {
        //Valid!
    } else {
        //Not valid.
    }
    

    It's advised to use this check only once and then reuse.

    P.S. Credits to Shachar for this function.

提交回复
热议问题