NSURL nil 因为有空格

NSURL nil because of spaces

端点不关心 URL 中是否有空格,但 NSURL 似乎有。

我每次 NSURL *url = [NSURL URLWithString:string]; 得到 nil:

NSString *string = [NSString stringWithFormat:@"http://endpoint.com/search?one=%@&two=%@", textField1.text, textField2.text];
NSURL *url = [NSURL URLWithString:string];
NSString *urlAbsolute = [url absoluteString];
[theManager GET:urlAbsolute parameters:nil progress:nil success:^(NSURLSessionTask * _Nonnull task, id  _Nullable responseObject) {

我想将空格传递到端点,因为我想从端点中获取空格。 (即传递 "Star Wars" ,所以如果我从字符串中删除空格,我会返回 "Star Wars" 而不是 "StarWars" )。

有什么想法吗?

使用允许字符的字符串编码 请找到以下代码。

NSString *string = [NSString stringWithFormat:@"http://endpoint.com/search?one=%@&two=%@", textField1.text, textField2.text];
NSURL *url = [NSURL URLWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]];

试试这个代码:

NSString *firstArgument = [self.textField1.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSString *secondArgument = [self.textField2.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

NSString *string = [NSString stringWithFormat:@"http://endpoint.com/search?one=%@&two=%@", firstArgument, secondArgument];
NSURL *url = [NSURL URLWithString:string];
NSString *urlAbsolute = [url absoluteString];