How to check validity of URL in Swift?

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

    This will return a boolean for a URL's validity, or nil if an optional URL with a value of nil is passed.

    extension URL {
    
        var isValid: Bool {
            get {
                return UIApplication.shared.canOpenURL(self)
            }
        }
    
    }
    

    Note that, if you plan to use a Safari view, you should test url.scheme == "http" || url.scheme == "https".

提交回复
热议问题