NSURL returns null, stringByAddingPercent... returns a nightmare
I'll try to be quick, I'm still pretty new but I can usually figure stuff out, this issue is driving me crazy. I have an XML on a web site, parse it into a table, click the item, load a link into a webView, and starts the issue...
-(void)viewDidLoad {
NSString *str = [NSString stringWithFormat:@"%@", [item objectForKey:@"link"]];
NSURL *url = [NSURL URLWithString = str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest = request];
}
If you NSLog *str, it's good. If you NSLog URL ,it's null. The issue is obviously using an objectForKey, 开发者_Python百科because otherwise everything else works. Now if I
NSURL *url = [NSURL URLWithString = [str stringByAddingPercentEscapesUsingEncoding:...
adding either NSUTF or NSASCII, the NSLog for URL adds
%0A%20%20%20%20%20%20%20%20%0A%20%20%0A%20%20
to end end of my value. So if the value was aq1sw2de3, the nslog would be
aq1sw2de3%0A%20%20 etc.
I just typed this up from lookin at the mac screen, assume all spelling errors don't exist in the code. I've tried so many different way of passing this URL to the webView, but my results are either NULL or all that damn gibberish. Am I wasting my time doing something I can't do? Am I going about it the wrong way? I've been searching for hours, and all the issues I see are due to formatting of the string or url they are passing ( spaces and | causing errors) but my link values are just A through Z and 0 through 9, that's it.
"%20" and "%0A" are the percent escape sequences for a space and a tab character, respectively. Check whether your string has some extra whitespace at the end.
Somehow, your string is getting picking up some extra whitespace. If you simply need to trim it, try:
NSURL *url = [NSURL URLWithString:
[[str stringByAddingPercentEscapesUsingEncoding: NSUTF8Encoding]
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
Scott's right. Look at the NSCharacterSet for a constant set of whitespace characters you can use to trim your string with. You can use the NSString call stringByTrimmingCharactersInSet with the whitespace set to remove unwanted characters.
精彩评论