NSString 和 NSUrl 未正确转换
因此,我尝试从来自 URL 的 XML 流中检索数据。该 URL 是根据用户输入的搜索字符串配置的。这段代码有什么理由不能工作吗?
NSString *searchString = "Geoff";
NSString *updatedURL = [NSString stringWithFormat:@"http://mysearchpage.com/searchQuery=%@", searchString];
NSLog(updatedURL);
NSURL *url = [[NSURL alloc] initWithString:updatedURL];
现在,这对于单个单词搜索来说效果很好,但是一旦我尝试搜索名字和姓氏,URL 每次都会返回 nil。字符串是否有任何行为可能导致这种情况?
当附加搜索字符串时,我什至尝试用“%20”替换“”,看看这是否是问题所在。我这样做是用:
NSURL *url = [[NSURL alloc] initWithString:[updatedURL stringByReplacingOccurrencesOfString:@" " withString:@"%%20"]];
有什么想法吗?提前致谢!
So I am trying to retrieve data from an XML stream coming from a URL. This URL is configured on a search string the user inputs. Is there any reason why this code should not be working?
NSString *searchString = "Geoff";
NSString *updatedURL = [NSString stringWithFormat:@"http://mysearchpage.com/searchQuery=%@", searchString];
NSLog(updatedURL);
NSURL *url = [[NSURL alloc] initWithString:updatedURL];
Now this works fine for single word searches, but as soon as I try and search for like a first and last name, the URL returns nil every time. Is there any behavior with the strings that may be causing that?
I have even tried to replace the " "'s with "%20"'s when the search string was appended to see if that was the problem. I did that using:
NSURL *url = [[NSURL alloc] initWithString:[updatedURL stringByReplacingOccurrencesOfString:@" " withString:@"%%20"]];
any ideas? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 NSString 的
-stringByAddingPercentEscapesUsingEncoding:
方法:You should use NSString's
-stringByAddingPercentEscapesUsingEncoding:
method for that:如果这确实是副本&粘贴您的代码,可能是因为
searchString
缺少@
符号。这应该是NSString *searchString = @"Geoff";
If this is indeed a copy & paste of your code, it might be because the
searchString
is missing the@
-sign. This should beNSString *searchString = @"Geoff";