所以我试图从来自 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"]];
有什么想法吗?提前致谢!
最佳答案
你应该使用 NSString 的 -stringByAddingPercentEscapesUsingEncoding:
方法:
NSURL *url = [[NSURL alloc] initWithString:
[updatedURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
关于objective-c - NSString 和 NSUrl 转换不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3408551/