Skip to content

Instantly share code, notes, and snippets.

@InsertNetan
Last active April 21, 2017 09:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InsertNetan/372c9f51549ea96e5af2 to your computer and use it in GitHub Desktop.
Save InsertNetan/372c9f51549ea96e5af2 to your computer and use it in GitHub Desktop.
get the value of a specific query item within NSURL
extension NSURL {
func getQueryItemValueForKey(key: String) -> String? {
guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else {
return nil
}
guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name == key
}.first?.value
}
}
@hemang-azilen
Copy link

Is it available for Objective-C?

@InsertNetan
Copy link
Author

@hemang-azilen
Didn't tried but i cant see any reason it won't work with ObjC.

@vinod1879
Copy link

This will fail if the query-param key has a case mismatch.
I would suggest improving it to:
$0.name.lowercaseString == key.lowercaseString

@InsertNetan
Copy link
Author

InsertNetan commented Jun 24, 2016

@vinod1879
I don't know if you always want a case insensitive check for your keys.
you can add extra parameter with a default value for case sensitive/insensitive check.
func getQueryItemValueForKey(key: String, isCasesensitive casesensitive: Bool = false ) -> String?
and apply the correct logic in the body of the function

@danipralea
Copy link

very nice. thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment