iosobjective-cnsurlnsurlrequest

How to remove paramters in NSURL's query in iOS?


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?


Solution

  • 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
                }