開發時常常會遇到要對api傳送參數的狀況,
但常常都是傳送String Int Bool等,
那假如是傳送一個連結呢?
但缺乏資訊背景的我,對於這種小陷阱,就這樣順順地跳下去了XD
原本我就想說String啊
跟一般的處理一樣,結果送出錯誤
排除是api的問題,那只能是要帶URL的參數值帶錯了,
帶出去的網址看起來是不完整的,從某些符號後就斷了,
再仔細看看應該是參數帶到了URL的保留字符(例如:”@“、”:”等等)、或是中文字等等,
所以需要進行URL Encode的處理(百分比編碼),
除了百分比和數字,還搭配16進制的大寫英文
網路上有很多線上URL ENCODE的資源可以使用
例如:https://www.urlencoder.org/
轉換範例:
https://www.google.com/search?client=safari&rls=en&q=url編碼&ie=UTF-8&oe=UTF-8
轉換後變成
https%3A%2F%2Fwww.google.com%2Fsearch%3Fclient%3Dsafari%26rls%3Den%26q%3Durl%E7%B7%A8%E7%A2%BC%26ie%3DUTF-8%26oe%3DUTF-8
從上面來看,encode後,將不再看到「:」、「//」、「?」、「=」、「&」和中文字,有處理過後的url才能當作參數值來傳送
那在swift要如何使用URL encode呢?swift 的函式庫有可用的,如下:
let url = “https://www.google.com/search?client=safari&rls=en&q=url編碼&ie=UTF-8&oe=UTF-8”
let urlEncoded = url!.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
網路上查詢到的字符集(CharacterSet)各是如下:
urlFragmentAllowed "#%<>[\]^`{|}
urlHostAllowed "#%/<>?@\^`{|}
urlPasswordAllowed "#%/:<>?@[\]^`{|}
urlPathAllowed "#%;<>?[\]^`{|}
urlQueryAllowed "#%<>[\]^`{|}
urlUserAllowed "#%/:<>?@[\]^`
若你需要encode其他特殊字符,也可以自訂字符集進行url encode
let url = “https://www.google.com/search?client=safari&rls=en&q=url編碼&ie=UTF-8&oe=UTF-8”
let newCharacterSet = CharacterSet(charactersIn: "!*'();:@=&+$,/?%#[] ").inverted
let urlEncoded = url!.addingPercentEncoding(withAllowedCharacters: newCharacterSet)