13

I have an URL that looks like myapp://jhb/test/deeplink/url?id=4567 . I want to delete every thing after the ? char. At the end the URL should look like myapp://jhb/test/deeplink/url. how. can I achieve that? convert the url to a string? Regex?

1

5 Answers 5

18

Use URLComponents to separate the different URL parts, manipulate them and then extract the new url:

var components = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567")!
components.query = nil
print(components.url!)

myapp://jhb/test/deeplink/url

Sign up to request clarification or add additional context in comments.

Comments

10

A convenient extension on URL


private extension URL {
    var removingQueries: URL {
        if var components = URLComponents(string: absoluteString) {
            components.query = nil
            return components.url ?? self
        } else {
            return self
        }
    }
}

Comments

4

can I achieve that? convert the url to a string? Regex?

When working with URLs, it would be better to treat it as URLComponent:

A structure that parses URLs into and constructs URLs from their constituent parts.

therefore, referring to URLComponent what are you asking is to remove the the query subcomponent from the url:

if var components = URLComponents(string: "myapp://jhb/test/deeplink/url?id=4567") {
    components.query = nil
    
    print(components) // myapp://jhb/test/deeplink/url
}

Note that query is an optional string, which means it could be nil (as mentioned in the code snippet, which should leads to your desired output).

Comments

0

You can do like this

let values = utl?.components(separatedBy: "?")[0]

It will break the string with ? and return the array. The first object of values give you your resultant string.

Comments

0

You can get each URL component separated from URl using

print("\(url.host!)") //Domain name
print("\(url.path)") // Path
print("\(url.query)") // query string

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.