Hello everyone I have an objective-c dilema :P I am quite new to objective-c, and I have tried searching for an answer, but to no avail.
So, here is my situation. I
If I understand you correctly, you're trying to generate a string with literal "%20"s embedded in it. The "%" character is special in format strings. If you want to insert a literal percent character, you need to escape it by putting two consecutive "%"s. Like
[NSURL URLWithString:[baseURLStr stringByAppendingFormat:@"foo%%20bar"]];
That would append "foo%20bar" to the end of the string.
You probably just need to encode the percent signs. Try: stringByAppendingFormat:@"announcements%%20%@%%20%d%%20carson.ashx"]
whenever an NSURL returns nil (0x0) after init it is almost always related to in improper url string. And its very picky about getting a properly formatted string.
my recommendation is to simply build your string, without any escapes or url encoding, then simply call
myUrlString = [myUrlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
here is the header declaration for it
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc NS_AVAILABLE(10_3, 2_0);
this way, I always know I get it formatted the way that the NSURL class wants it.
here is an example
NSString *sUrl = @"http://www.myside.ca/example/announcements carson.ashx"; //notice the embedded space
sUrl = [sUrl stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:sUrl];
If you're not using printf-style formats, don't use stringByAppendingFormat:
. Use stringByAppendingString:
instead.
Second, is the resulting URL really supposed to be http://www.myside.ca/exampleannouncements%20%@%20%d%20carson.ashx
? Or is there supposed to be a slash in the middle: http://www.myside.ca/example/announcements%20%@%20%d%20carson.ashx
?
Also, http://www.myside.ca/exampleannouncements%20%@%20%d%20carson.ashx
is an invalid URL. The percent signs that are not part of an escape (e.g. not part of %20
) must themselves be encoded, as %25
. Technically, the @
should also be escaped (as %40
), but IIRC NSURL will let that slide.