如何验证网址是否有效?
说我有这个网址:
问题:
我需要按如下方式验证网址:
确保网址有效检查方案:使用的方案:HTTP
或HTTPS
如果它位于URL
url = http://host/absolutePath
示例:
我试试这个:
var strURL = NSURL(string:"http://www.example.com:80/dir/?query=test")
if(strURL?scheme == "http" && strURL?scheme == "https"){
// remove the Port No
} else {
}
如何删除端口号并将URL重建为字符串?
答案 0 :(得分:0)
您可以使用URLComponents
func validate(url : String) -> String? {
guard var components = URLComponents(string: url),
(components.scheme == "http" || components.scheme == "https") else { return nil }
components.port = nil
return components.string
}
let strURL = "http://www.example.com:80/dir/?query=test"
let url = validate(url: strURL) // "http://www.example.com/dir/?query=test"
答案 1 :(得分:0)
检查这是否有帮助
func testUrl(string: String) -> String? {
var stringUrl: String?
if let url = URL(string: string){
if url.scheme == "http" || url.scheme == "https"{
stringUrl = url.absoluteString
if let port = url.port{
stringUrl = stringUrl?.replacingOccurrences(of: ":\(port)", with: "")
}
}
}
return stringUrl
}