NSString and NSUrl not converting properly

拈花ヽ惹草 提交于 2019-12-13 15:30:28

问题


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!


回答1:


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

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



回答2:


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



来源:https://stackoverflow.com/questions/3408551/nsstring-and-nsurl-not-converting-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!