LoginSignup
0
0

More than 3 years have passed since last update.

在 URLComponent 使用 URLQueryItem

Last updated at Posted at 2019-08-01

在 URLComponent 這個 class 裡面,可以用 URLQueryItem 定義的方式,在不需要自己編碼的情形下,就可以輕鬆設定好網址中的 query string 。

Query String

維基百科: https://en.wikipedia.org/wiki/Query_string

// 範例網址
https://example.com?item%20type=%E7%94%A2%E5%93%81&size=small&current

簡單來說,就是問號後面,以 key/value 成對的存在或是只有 key (如下表),用 & 串起來的字串。

Original Key Original Value Encoded Key Encoded Value
item type 產品 item%20type %E7%94%A2%E5%93%81
size small size small
current current

優點

在 key 或是 value 裡面有空白或是網址不友善的字串的時候,都需要自己把那些字串轉換成適當的字串 (URL encode) 。但是 URLQueryItem 則可以直接幫忙編碼就不需要自己處理了。

用法

首先先建立一個簡易的 URLComponent

var component = URLComponents(string: "https://example.com")

接著只要這樣設定 query items 即可不需要自己做 URL encode,

component?.queryItems = [
    URLQueryItem(name: "item key", value: "產品"),
    URLQueryItem(name: "size", value: "small"),
    URLQueryItem(name: "current", value: nil)
]

印印看

print(component?.url)

看 console output ,就可以發現她幫我們很漂亮的編碼完了:

Optional(https://example.com?item%20type=%E7%94%A2%E5%93%81&size=small&current)

以上。

環境

這篇的程式碼在以下的環境中正常執行:

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5
  • Playground

參考連結

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0