Encode '+' using URLComponents in Swift

前端 未结 4 793
死守一世寂寞
死守一世寂寞 2020-12-11 00:56

This is how I add query params to a base URL:

let baseURL: URL = ...
let queryParams: [AnyHashable: Any] = ...
var components = URLComponents(url: baseURL, r         


        
4条回答
  •  一生所求
    2020-12-11 01:19

    Can you try using addingPercentEncoding(withAllowedCharacters: .alphanumerics)?

    I just put together a quick playground demonstrating how this works:

    //: Playground - noun: a place where people can play
    
    let baseURL: URL = URL(string: "http://example.com")!
    let queryParams: [AnyHashable: Any] = ["test": 20, "test2": "+thirty"]
    var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)
    
    var escapedComponents = [String: String]()
    for item in queryParams {
        let key = item.key as! String
        let paramString = "\(item.value)"
    
        // percent-encode any non-alphanumeric character.  This is NOT something you typically need to do.  User discretion advised.
        let escaped = paramString.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
    
        print("escaped: \(escaped)")
    
        // add the newly escaped components to our dictionary
        escapedComponents[key] = escaped
    }
    
    
    components?.queryItems = escapedComponents.map { URLQueryItem(name: ($0), value: "\($1)") }
    let finalURL = components?.url
    

提交回复
热议问题