1

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?

2 Answers 2

6

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; 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.