Let\'s say I have an NSURL
? Whether or not it already has an empty query string, how do I add one or more parameters to the query
of the NSUR
The answers above mentioned the NSURLComponents,it's a good class to handle URL.
My answer is as follows:
Create a category with NSURL,like NSURL+Additions.h. Then,add the following method and implement it.
- (NSURL *)URLByAppendingQueryParameters:(NSDictionary *)queryParameters
{
if (queryParameters.count == 0) {
return self;
}
NSArray *queryKeys = [queryParameters allKeys];
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:self resolvingAgainstBaseURL:NO];
NSMutableArray * newQueryItems = [NSMutableArray arrayWithCapacity:1];
for (NSURLQueryItem * item in components.queryItems) {
if (![queryKeys containsObject:item.name]) {
[newQueryItems addObject:item];
}
}
for (NSString *key in queryKeys) {
NSURLQueryItem * newQueryItem = [[NSURLQueryItem alloc] initWithName:key value:queryParameters[key]];
[newQueryItems addObject:newQueryItem];
}
[components setQueryItems:newQueryItems];
return [components URL];
}
I have an extension to NSURLComponents
that add query item, in swift:
extension NSURLComponents {
func appendQueryItem(name name: String, value: String) {
var queryItems: [NSURLQueryItem] = self.queryItems ?? [NSURLQueryItem]()
queryItems.append(NSURLQueryItem(name: name, value: value))
self.queryItems = queryItems
}
}
To use,
let components = NSURLComponents(string: urlString)!
components.appendQueryItem(name: "key", value: "value")