How to check validity of URL in Swift?

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

    Version that works with Swift 4.2 and has reliable URL pattern matching ...

    func matches(pattern: String) -> Bool
    {
        do
        {
            let regex = try NSRegularExpression(pattern: pattern, options: [.caseInsensitive])
            return regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: utf16.count)) != nil
        }
        catch
        {
            return false
        }
    }
    
    
    func isValidURL() -> Bool
    {
        guard let url = URL(string: self) else { return false }
        if !UIApplication.shared.canOpenURL(url) { return false }
    
        let urlPattern = "(http|ftp|https):\\/\\/([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?"
        return self.matches(pattern: urlPattern)
    }
    

提交回复
热议问题