How to check validity of URL in Swift?

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

    Helium having to deal with various schemes:

    struct UrlHelpers {
        // Prepends `http://` if scheme isn't `https?://` unless "file://"
        static func ensureScheme(_ urlString: String) -> String {
            if !(urlString.lowercased().hasPrefix("http://") || urlString.lowercased().hasPrefix("https://")) {
                return urlString.hasPrefix("file://") ? urlString : "http://" + urlString
            } else {
                return urlString
            }
        }
    
        // https://mathiasbynens.be/demo/url-regex
        static func isValid(urlString: String) -> Bool {
            // swiftlint:disable:next force_try
            if urlString.lowercased().hasPrefix("file:"), let url = URL.init(string: urlString) {
                return FileManager.default.fileExists(atPath:url.path)
            }
    
            let regex = try! NSRegularExpression(pattern: "^(https?://)[^\\s/$.?#].[^\\s]*$")
            return (regex.firstMatch(in: urlString, range: urlString.nsrange) != nil)
        }
    }
    

提交回复
热议问题