How to check validity of URL in Swift?

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

    This accepted answer doesn't work in my case with wrong url without data https://debug-cdn.checkit4team.com/5/image/Y29tbW9uL2RlZmF1bHRfYXZhdGFyLnBuZw==

    So I write extension to solve

    extension String {
        var verifyUrl: Bool {
            get {
                let url = URL(string: self)
    
                if url == nil || NSData(contentsOf: url!) == nil {
                    return false
                } else {
                    return true
                }
            }
        }
    }
    

    Use it:

    if string. verifyUrl {
        // do something
    }
    

    Hope this help!

提交回复
热议问题