-2

I'm trying to get the parameters from a URL using Swift. Let's say I have the following URL:

https://test.page.link/foo?accessCode=GA362078&bar=test

How can I get the value of foo?accessCode (GA362078), and bar (test)?

Han
  • 74
  • 1
  • 10
  • 1
    You can get all the parts of an URL using `NSURLComponents`. See https://developer.apple.com/documentation/foundation/nsurlcomponents?language=swift – koen Oct 12 '20 at 16:20
  • The URL Components returned will be ["/", "foo"]. Where I'm stuck is that I need to be able to get the value from foo?accessCode= and &bar= – Han Oct 12 '20 at 16:26
  • I believe they are in `queryItems`. – koen Oct 12 '20 at 16:28
  • https://stackoverflow.com/questions/41421686/get-the-value-of-url-parameters https://stackoverflow.com/questions/8756683/best-way-to-parse-url-string-to-get-values-for-keys etc. – Larme Oct 12 '20 at 16:33

1 Answers1

1

Use the queryItems of URLComponents:

func value(for name: String, in urlString: String, with path: String) -> String? {
    if let components = URLComponents.init(string: urlString) {
        if components.path == path {
            return components.queryItems?.first { $0.name == name }?.value
        }
        else {
            return("Not found")
        }
    }

    return nil
}

let urlString  = "https://test.page.link/foo?accessCode=GA362078&bar=test"

if let accessCodeValue = value(for: "accessCode", in: urlString, with: "/foo") {
    print(accessCodeValue)
}

Output:

GA362078
koen
  • 5,383
  • 7
  • 50
  • 89
  • What about using `URLComponents` instead of `NSURLComponents` in recent Swift? – Larme Oct 12 '20 at 16:32
  • Is there a way to pass "foo" in a method parameter to return "GA362078" while also being able to pass in "bar" to get "test"? – Han Oct 12 '20 at 16:38
  • @Han just get the QueryItem properties (name `items[0].name` and value `items[0].value`). Btw `/foo` is the path not a query item – Leo Dabus Oct 12 '20 at 16:39
  • I guess ideally I would like to look for the foo path and retrieve the following accessCode query item with its value – Han Oct 12 '20 at 16:44
  • @Han: see update in my answer – koen Oct 12 '20 at 17:06
  • 1
    @koen just return `first {$0.name == name }?.value` – Leo Dabus Oct 12 '20 at 17:22
  • @LeoDabus - thanks, and I guess that one liner can even just go in the main function, no need for an extension? – koen Oct 12 '20 at 17:42
  • 1
    This is up to you. I like using extensions to avoid duplicating code but as you said it is just one line. – Leo Dabus Oct 12 '20 at 17:53