Home > Net >  How to remove paramters in NSURL's query in iOS?
How to remove paramters in NSURL's query in iOS?

Time:07-22

I use this string to build NSURL

https://123.com?p1=AA&p2=BB&p3=CC

and I want to remove the p1 & p2 paramter,just left the p3 only:

https://123.com?p3=CC

Is there any nicer way than the string compare&delete?

CodePudding user response:

guard let urlFromString = URL(string: "https://123.com?p1=AA&p2=BB&p3=CC") else {
return
}

var url = urlFromString

Get the url without query params:

var components = URLComponents(url: url, resolvingAgainstBaseURL: true)
components?.query = nil // remove the query
url = components.url

create a QueryParams dictionary :

let stringDictionary = [
"p3": "CC"
]

create final url :

 guard let newURl = url.append(queryParameters: stringDictionary) else {
                return
            } 

CodePudding user response:

You can modify queryItems of URLComponents directly

if var urlComponents = URLComponents(string: "https://123.com?p1=AA&p2=BB&p3=CC") {
    let parametersToRemove = ["p1", "p2"]
    urlComponents.queryItems?.removeAll{parametersToRemove.contains($0.name)}
    let finalURL = urlComponents.url!
    print(finalURL)
}
  • Related