4

I'm writing a mini-console of sorts and I'm trying to figure out how to extract things from a link. For example, in PHP this is a request variable so:

http://somelink.com/somephp.php?variable1=10&variable2=20

Then PHP figures out the url parameters and assigns them to a variable.

How would I parse something like this in Swift?

So, given the string I'd want to take: variable1=10 and variable2=20 etc, is there a simple way to do this? I tried googling around but didn't really know what I was searching for.

I have a really horrible hacky way of doing this but it's not really extendable.

Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
Scott
  • 309
  • 2
  • 13

1 Answers1

7

You’d be wanting NSURLComponents:

import Foundation

let urlStr = "http://somelink.com/somephp.php?variable1=10&variable2=20"
let components = NSURLComponents(string: urlStr)

components?.queryItems?.first?.name   // Optional("variable1")
components?.queryItems?.first?.value  // Optional("10")

You might find it helpful to add a subscript operator for the query items:

extension NSURLComponents {
    subscript(queryItemName: String) -> String? {
        // of course, if you do this a lot, 
        // cache it in a dictionary instead
        for item in self.queryItems ?? [] {
            if item.name == queryItemName {
                return item.value
            }
        }
        return nil
    }
}

if let components = NSURLComponents(string: urlStr) {
    components["variable1"] ?? "No value"
}
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118
  • hmm components?.queryItems?.first?.value doesn't seem to return anything? – Scott May 21 '15 at 23:16
  • also what about variable2? or any other variable other than first? – Scott May 21 '15 at 23:17
  • `first` is just a quick way to get the first value in an array while being safe in case the array is empty (unlike `queryItems?[0]` which will blow up if there are no query items. For multiple values, you can do `for…in` over it, have added more code. – Airspeed Velocity May 21 '15 at 23:18