How to check validity of URL in Swift?

后端 未结 22 1724
不知归路
不知归路 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:18

    Using 'canOpenUrl' was too expensive for my use case, I found this approach to be quicker

    func isStringLink(string: String) -> Bool {
        let types: NSTextCheckingResult.CheckingType = [.link]
        let detector = try? NSDataDetector(types: types.rawValue)
        guard (detector != nil && string.characters.count > 0) else { return false }
        if detector!.numberOfMatches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, string.characters.count)) > 0 {
            return true
        }
        return false
    }
    

提交回复
热议问题