NSString 和 NSUrl 未正确转换

发布于 2024-09-13 02:01:52 字数 613 浏览 4 评论 0原文

因此,我尝试从来自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为你鎻心 2024-09-20 02:01:52

您应该使用 NSString 的 -stringByAddingPercentEscapesUsingEncoding: 方法:

NSURL *url = [[NSURL alloc] initWithString:
   [updatedURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

You should use NSString's -stringByAddingPercentEscapesUsingEncoding: method for that:

NSURL *url = [[NSURL alloc] initWithString:
   [updatedURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
可可 2024-09-20 02:01:52

如果这确实是副本&粘贴您的代码,可能是因为 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 be NSString *searchString = @"Geoff";

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文