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.
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.
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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.