Home > Software design >  Get the value of URL Parameters in WKWebView and create new URL
Get the value of URL Parameters in WKWebView and create new URL

Time:11-29

I'm trying to get the current URL of the WKWebView, search/copy one value out of it, and create a new URL.

I use Swift and have this an URL like that https://example.org/bundle-572974a2.html and try to get the following value 572974a2. My intention is to create a new URL with that value. The numbers can change from time to time.

I use this code to get the current WKWebView URL. I think I have to convert this to a string first.

let oldURL = webView.url

And I use this code to create my new URL.

var components = URLComponents()
        components.scheme = "https"
        components.host = "new-example.org"
        components.path = "/g"

        components.queryItems = [
            URLQueryItem(name: "newbundle", value: "XXXXXXXX")
        ]
        
        let newURL = components.url

How can I change/paste the value: "XXXXXXXX" with the value 572974a2 of the old URL?

CodePudding user response:

Some simple URL manipulation and string handling will get you the number from the old URL:

let oldURL = URL(string: "https://example.org/bundle-572974a2.html")! // An example
let name = oldURL.deletingPathExtension().lastPathComponent // bundle-572974a2
let number = name.dropFirst(7) // remove "bundle-"

This assumes the number will always be preceded by "bundle-" (or any seven-letter sequence really. If that can vary then the use of dropFirst(7) will need to be replaced with code that can handle strings like "bundle-572974a2" and remove the part you don't want.

Then building the new URL becomes:

var components = URLComponents()
components.scheme = "https"
components.host = "new-example.org"
components.path = "/g"

components.queryItems = [
    URLQueryItem(name: "newbundle", value: String(number))
]
        
let newURL = components.url

In a case where you might have both a prefix and a suffix you need to remove, the following would be one way to remove them. This code assumes there will be a prefix to remove if there is a suffix to remove. If there is a suffix and no prefix to remove then this code gives the wrong result.

var number = url.deletingPathExtension().lastPathComponent
if let hyphen = number.firstIndex(of: "-") {
    number = String(number[number.index(after: hyphen)...])
}
if let hyphen = number.lastIndex(of: "-") {
    number = String(number[..<hyphen])
}

P.S. String manipulation in Swift is a pain.

  • Related