How to check validity of URL in Swift?

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

    This is for latest Swift 4, based on Doug Amos answer (for swift 3)

    public static func verifyUrl (urlString: String?) -> Bool {
        //Check for nil
        if let urlString = urlString {
            // create NSURL instance
            if let url = NSURL(string: urlString) {
                // check if your application can open the NSURL instance
                return UIApplication.shared.canOpenURL(url as URL)
            }
        }
        return false
    }
    

提交回复
热议问题