How to check validity of URL in Swift?

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

    In some cases it can be enough to check that the url satisfies RFC 1808. There are several ways to do this. One example:

    if let url = URL(string: urlString), url.host != nil {
      // This is a correct url
    }
    

    This is because .host, as well as .path, .fragment and a few other methods would return nil if url doesn't conform to RFC 1808.

    If you don't check, you might have this kind of messages in console log:

    Task .<72> finished with error - code: -1002
    

提交回复
热议问题