How to check validity of URL in Swift?

后端 未结 22 1781
不知归路
不知归路 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 isn't a regex approach, but it is a naive one that works well for making sure there is a host and an extension if you want a simple and inexpensive approach:

    extension String {
        var isValidUrlNaive: Bool {
            var domain = self
            guard domain.count > 2 else {return false}
            guard domain.trim().split(" ").count == 1 else {return false}
            if self.containsString("?") {
                var parts = self.splitWithMax("?", maxSplit: 1)
                domain = parts[0]
            }
            return domain.split(".").count > 1
        }
    }
    

    Use this only if you want a quick way to check on the client side and you have server logic that will do a more rigorous check before saving the data.

提交回复
热议问题