前提
functionを定義する方法
func generateDictionalyFromUrlComponents(components: NSURLComponents) -> [String : String] {
var fragments: [String : String] = [:]
guard let items = components.queryItems else {
return fragments
}
for item in items {
fragments[item.name] = item.value
}
return fragments
}
let comp: NSURLComponents? = NSURLComponents(string: "http://example.com/?id=12345&username=tarou")
let fragments = generateDictionalyFromUrlComponents(comp!)
print(fragments["id"])
NSURLをextensionする方法
extension NSURL {
var fragments: [String : String] {
var results: [String : String] = [:]
guard let urlComponents = NSURLComponents(string: self.absoluteString), let items = urlComponents.queryItems else {
return results
}
for item in items {
results[item.name] = item.value
}
return results
}
}
let url = NSURL(string: "http://example.com/?id=12345&username=tarou")
print(url!.fragments["id"])
雑感
- NSURLComponentsとNSURLQueryItemは便利
- 雑にググったら正規表現祭りで地獄かと思った