简体   繁体   English

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

[英]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. 多年来,将查询字符串添加到NSURL的最佳方法似乎已经发生了变化。 Here is one from 2009 and here they are from 2014 . 这是2009年的作品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. 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;

The correct way to form any kind of NSURL is to use NSURLComponents. 形成任何类型的NSURL的正确方法是使用NSURLComponents。 Manipulating a string directly is always wrong. 直接操作字符串总是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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