简体   繁体   中英

2018 way to add a querystring to an NSURL in Objective-C

The best way to add a querystring to an NSURL seems to have changed over the years. Here is one from 2009 and here they are from 2014 . All of the approaches seem rather heavy for such a seemingly simple task.

The following code is not working for me:

#define kWeatherStemURL [NSURL URLWithString: @"https://api.openweathermap.org/data/2.5/weather?units=imperial&APPID=xxxxxxx"];
NSURL* startingUrl = kWeatherStemURL;
NSString *querystring = @"&lat=35&lon=139";
NSURL *dataUrl = [NSURL URLWithString:[startingUrl.path stringByAppendingString:querystring]];

What is the best way to do it today?

A modern way is NSURLComponents and NSURLQueryItem , it even applies percent encoding if needed.

NSURLComponents *components = [NSURLComponents componentsWithString: @"https://api.openweathermap.org/data/2.5/weather"];
NSArray<NSURLQueryItem *> *queryItems = @[[NSURLQueryItem queryItemWithName:@"units" value:@"imperial"],
                                          [NSURLQueryItem queryItemWithName:@"APPID" value:@"xxxxxxx"],
                                          [NSURLQueryItem queryItemWithName:@"lat" value:@"35"],
                                          [NSURLQueryItem queryItemWithName:@"lon" value:@"139"]];
components.queryItems = queryItems;
NSURL *dataUrl = components.URL;

The correct way to form any kind of NSURL is to use NSURLComponents. Manipulating a string directly is always wrong.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM