Reputation: 2007
I have an NSString
. It is a URL I am getting when using Universal Links. I want to get id value from it. Is there any direct methods in SDK or do we need to use componententsSeparated
String values?
Below is the NSString/URL:
I want to get two things: "test" from test.html and "id" value.
Upvotes: 0
Views: 431
Reputation: 3013
We can make extension
extension URL {
func getParamValue(paramaterName: String) -> String? {
guard let url = URLComponents(string:self.absoluteString ) else { return nil }
return url.queryItems?.first(where: { $0.name == paramaterName})?.value
}
}
Now you can call like below
let someURL = URL(string: "https://some.com/cc/test.html?id=3039&value=test")!
someURL.getParamValue("id") // 3039
someURL.getParamValue("value") // test
Upvotes: 1
Reputation: 16160
You could create NSURLComponents
from URL string get parameters by calling queryItems
method. It will return array of NSURLQueryItem
NSURLComponents *components = [NSURLComponents componentsWithString:@"https://some.com/cc/test.html?id=3039&value=test"];
NSArray *array = [components queryItems];
for(NSURLQueryItem *item in array){
NSLog(@"Name: %@, Value: %@", item.name, item.value);
}
NSLog(@"Items: %@", array);
Upvotes: 1
Reputation: 318814
Use NSURLComponents
created from an NSURL
or NSString
of your URL.
From there you can use path
to get the /cc/test.html
part. Then use lastPathComponent
to get test.html
and finally use stringByDeletingPathExtension
to get test
.
To get the "id" value start with the components' queryItems
value. Iterate that array finding the NSURLQueryItem
with the name of "id" and then get its value.
Upvotes: 1