端点不关心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) {
我想将空间传递到端点中,因为我想从端点中获得空间。(也就是说,把"星球大战"传进去,所以如果我从字符串中去掉空格,我会把"星球战争"而不是"星球大战》"拿出来)。
有什么想法吗?
使用允许字符的字符串编码请查找以下代码。
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];