Swift - encode URL

后端 未结 17 1868
無奈伤痛
無奈伤痛 2020-11-21 22:20

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  情书的邮戳
    2020-11-21 23:07

    You can use URLComponents to avoid having to manually percent encode your query string:

    let scheme = "https"
    let host = "www.google.com"
    let path = "/search"
    let queryItem = URLQueryItem(name: "q", value: "Formula One")
    
    
    var urlComponents = URLComponents()
    urlComponents.scheme = scheme
    urlComponents.host = host
    urlComponents.path = path
    urlComponents.queryItems = [queryItem]
    
    if let url = urlComponents.url {
        print(url)   // "https://www.google.com/search?q=Formula%20One"
    }
    

    extension URLComponents {
        init(scheme: String = "https",
             host: String = "www.google.com",
             path: String = "/search",
             queryItems: [URLQueryItem]) {
            self.init()
            self.scheme = scheme
            self.host = host
            self.path = path
            self.queryItems = queryItems
        }
    }
    

    let query = "Formula One"
    if let url = URLComponents(queryItems: [URLQueryItem(name: "q", value: query)]).url {
        print(url)  // https://www.google.com/search?q=Formula%20One
    }
    

提交回复
热议问题