2018 在 Objective-C 中向 NSURL 添加查询字符串的方法

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

多年来,向 NSURL 添加查询字符串的最佳方式似乎有所改变。这是 2009 and here they are from 2014 中的一个。对于这样一个看似简单的任务,所有的方法似乎都相当繁重。

以下代码对我不起作用:

#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]];

今天最好的方法是什么?

一种现代的方式是 NSURLComponentsNSURLQueryItem,如果需要,它甚至可以应用百分比编码。

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;

形成任何类型的 NSURL 的正确方法是使用 NSURLComponents。直接操作字符串总是错误的。