Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active May 9, 2019 02:42
Show Gist options
  • Save KentarouKanno/d1901dcd573f091485b06ff794ad6e9d to your computer and use it in GitHub Desktop.
Save KentarouKanno/d1901dcd573f091485b06ff794ad6e9d to your computer and use it in GitHub Desktop.
URLComponents

URLComponents

let urlString = "http://user:password@www.example.com:8080/hoge/fuga/index.html?a=1&b=2#test"

let components = URLComponents(string: urlString)

print("scheme :",components?.scheme ?? "")
/* scheme : http */

print("user :",components?.user ?? "")
/* user : user */

print("password :",components?.password ?? "")
/* password : password */

print("host :", components?.host ?? "")
/* host : www.example.com */

print("port :", components?.port ?? "")
/* port : 8080 */

print("path :",components?.path ?? "")
/* path : /hoge/fuga/index.html */

print("query :",components?.query ?? "")
/* query : a=1&b=2 */

print("fragment :",components?.fragment ?? "")
/* fragment : test */

print("queryItems :", components?.queryItems ?? "")
/* queryItems : [a=1, b=2] */

if let queryItems = components?.queryItems {
    for queryItem in queryItems {
        print("\(queryItem.name): \(queryItem.value)")
        // a: Optional("1")
        // b: Optional("2")
    }
}

// URLComponents RangeOf〜
if let rangeOfScheme = components?.rangeOfScheme {
    
    let scheme1 = urlString[rangeOfScheme]
    //=> http
    let scheme2 = urlString[rangeOfScheme.lowerBound ..< rangeOfScheme.upperBound]
    //=> http
}
  • queryItems → [String : String]
extension URL {
     func queryParams() -> [String : String] {
         var params = [String : String]()

          guard let comps = URLComponents(string: self.absoluteString) else {
             return params
         }
         guard let queryItems = comps.queryItems else { return params }

          for queryItem in queryItems {
             params[queryItem.name] = queryItem.value
         }
         return params
     }
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment