Swift建立URL

Henry Huang
3 min readJan 31, 2019

--

在Swift,我之前也是一直都直接用這樣建立一個URL:

if let url = URL(string: "填入字串") {print(url)}

這樣就可以建立一個URL,但有次在連接一個第三方API,然後再做測試時一直發生問題…連不到,才發現原來創建URL失敗。

URL是URI的一個應用,借一下維基百科的圖就可以清楚知道URI的格式

主要就是由scheme、authority、path、query、fragment組成,但並不一定全部都一定要使用

像是:https://example.com/v1/player?name=allen%20iverson

上面這個URL就只有scheme:https、 host:example.com、path:/v1/player、query:allen%20iverson組成

使用平常最常使用的方式創建一個URL

if let url = URL(string: "https://example.com/v1/player?name=allen%20iverson") {print(url)} else {print("錯誤URL")}

會印出https://example.com/v1/player?name=allen%20iverson

沒什麼問題,但注意到那個%20,這是因為URl不能有特殊字元如空白等,%20就是空白經過URL encoding後的編碼。

當然…在URL裡也是不能出現中文的,這也是我上次的問題(弱😅)

if let url = URL(string: "https://example.com/v1/player?name=艾佛森") {print(url)} else {print("錯誤URL")}

印出:錯誤URL,必須寫中文字對印的編碼才可以,但我怎麼可能知道他的編碼…哈哈

所以可以用另一個叫做URLComponents,雖然使用步驟稍微多一些,但也滿容易使用,以下:

var urlComponent = URLComponents() urlComponent.scheme = "https" urlComponent.host = "example.com" urlComponent.path = "/v1/player" urlComponent.queryItems = [ URLQueryItem(name: "name", value: "allen%20iverson") ]if let url = urlComponent.url { print(url) } else { print("錯誤URL") }

會印出https://example.com/v1/player?name=allen%20iverson

可以得到相同結果,重點來了,厲害的地方就是URLQueryItem,在這裡面其實是可以直接打成 URLQueryItem(name: “name”, value: “allen iverson”) ->

印出https://example.com/v1/player?name=allen%20iverson

甚至是中文也可以URLQueryItem(name: “name”, value: “艾佛森”) ->

印出https://example.com/v1/player?name=%E8%89%BE%E4%BD%9B%E6%A3%AE

自動幫我們URL encoding,舒服😆

--

--

Henry Huang

大學讀企管/退伍後在業務圈打滾6年後突然有一天決定投入完全沒接觸過的程式設計/目前為一位iOS Developer/熱愛NBA/dafu1231@gmail.com