NSString 和 NSUrl 无法正确转换 [英] NSString and NSUrl not converting properly

查看:57
本文介绍了NSString 和 NSUrl 无法正确转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从来自 URL 的 XML 流中检索数据.此 URL 是在用户输入的搜索字符串上配置的.这段代码有什么理由不能工作吗?

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];

现在这适用于单个单词搜索,但是一旦我尝试搜索名字和姓氏,URL 每次都返回 nil.是否有任何可能导致这种情况的字符串行为?

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?

当附加搜索字符串时,我什至尝试将""替换为%20"以查看是否是问题所在.我这样做了:

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!

推荐答案

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

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

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

这篇关于NSString 和 NSUrl 无法正确转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆