2017-08-29 89 views
0

如何驗證網址是否有效?如何驗證網址有效

說我有這個網址:

http://www.example.com:80/dir/?query=test

問題:

我需要驗證網址如下:

  1. 確保網址有效檢查方案:該方案用於:HTTPHTTPS

  2. 刪除端口號,如果它是在URL

  3. 返回一個絕對的URL字符串得到主機,獲取路徑如下

URL = http://host/absolutePath

實施例:

https://www.example.com/dir/?query=test

我試試這個:

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

你可以做到這一點與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" 
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 
    }