LoginSignup
11
12

More than 5 years have passed since last update.

[Swift] パーセントエンコードを自作関数でやる必要は無かった

Last updated at Posted at 2017-07-26

ちょっとHTTP GET/POSTしたい時にパラメータ類をパーセントエンコードする必要があり、以下のようなコードでエンコードしていましたが

/// パーセントエンコードを行う
func percentEncode(_ str: String) -> String {
    var characterSet = CharacterSet.alphanumerics
    characterSet.insert(charactersIn: "-._~")
    return str.addingPercentEncoding(withAllowedCharacters: characterSet)!
}

let url = "http://hoge.jp/test_api?en=\(percentEncode("english"))&jp=\(percentEncode("日本語"))&other=\(percentEncode("&=+"))"

print(url) // http://hoge.jp/test_api?en=english&jp=%E6%97%A5%E6%9C%AC%E8%AA%9E&other=%26%3D%2B

(せめてURL構築関数を作るべきというツッコミは横に置いておきます)

そもそもその手の機能がiOS8で用意されているようなので、今後はこちらを積極的に使っていこうと思います。
URLComponents自体はiOS7から有りますが、queryItemsプロパティなどはiOS8以上)

var urlComponents = URLComponents(string: "http://hoge.jp/test_api")!
urlComponents.queryItems = [
    URLQueryItem(name: "en", value: "english"),
    URLQueryItem(name: "jp", value: "日本語"),
    URLQueryItem(name: "other", value: "&=+"),
]

print(urlComponents.url ?? "") // http://hoge.jp/test_api?en=english&jp=%E6%97%A5%E6%9C%AC%E8%AA%9E&other=%26%3D+

POSTのBODYにはこっちを使うと便利そうです。

print(urlComponents.percentEncodedQuery ?? "") // en=english&jp=%E6%97%A5%E6%9C%AC%E8%AA%9E&other=%26%3D+

URLComponents自体は過去にqiitaでも何度か紹介されていましたが、すっかり見落としていました。

おまけ

URLComponentsを使ったURL構築関数も作ってみました。

func buildUrl(base: String, namedValues: [(name: String, value: String)]) -> URL? {
    guard var urlComponents = URLComponents(string: base) else { return nil }
    urlComponents.queryItems = namedValues.map { URLQueryItem(name: $0.name, value: $0.value) }
    return urlComponents.url
}

print(buildUrl(base: "http://hoge.jp/test_api", namedValues: [("en", "english"), ("jp", "日本語"), ("other", "&=+")]))
11
12
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
11
12