How to check validity of URL in Swift?

后端 未结 22 1745
不知归路
不知归路 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条回答
  •  Happy的楠姐
    2020-11-29 02:07

    Try this:

    func isValid(urlString: String) -> Bool
    {
        if let urlComponents = URLComponents.init(string: urlString), urlComponents.host != nil, urlComponents.url != nil
        {
            return true
        }
        return false
    }
    

    This simply checks for valid URL components and if the host and url components are not nil. Also, you can just add this to an extensions file

提交回复
热议问题