How to correctly escape a % symbol - ios

I'm having trouble getting a string URL to format correctly. The desired output is this:
http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=1&max-results=50&v=2&fields=entry%5Blink/#rel='http://gdata.youtube.com/schemas/2007%23mobile'%5D
This is the code I started with:
NSString *urlRequest = [NSString stringWithFormat:#"http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=%u&max-results=%u&v=2&fields=entry[link/#rel='http://gdata.youtube.com/schemas/2007%23mobile']", dataStartIndex, dataIncrements];
NSURL *url = [NSURL URLWithString:urlRequest];
It keeps garbling the '%23mobile' at the end and making it '20072obile'. I tried using a \ before the # symbol but that didn't work. What am I doing wrong?
Strangely, it works correctly if I break it into 2 pieces like this:
NSString *urlRequest = [NSString stringWithFormat:#"http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=%u&max-results=%u&v=2&fields=entry", dataStartIndex, dataIncrements];
NSURL *url = [NSURL URLWithString:[urlRequest stringByAppendingString:#"[link/#rel='http://gdata.youtube.com/schemas/2007%23mobile']"]];
It also works if I do it without any arguments (dataStartIndex, dataIncrements).

You need to escape the %23 with another %, to make 2007%%23mobile. For example:
NSString *urlRequest = [NSString stringWithFormat:#"http://gdata.youtube.com/feeds/api/videos?q=corgi&start-index=%u&max-results=%u&v=2&fields=entry[link/#rel='http://gdata.youtube.com/schemas/2007%%23mobile']", dataStartIndex, dataIncrements];

You can use :-
NSString *string=[#"yourUrlString" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Add an extra % to escape the %, since the string you provided is a format string, not plain string.

Related

Strange Issue with NSURL with Xocode6.1

I have a strange issue with Xcode6.1
_mainURl is my ' ServerLink '
service is ' GetUserById '
NSString* str = [NSString stringWithFormat:#"%#%#",_mainURl,service];
NSURL *url = [NSURL URLWithString:str];
When I append two strings and Create a url with NSURL, url getting 'null'
But, When I directly given the server link followed by serviceName I can generate URL.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"ServerLink/GetUserById"]];
Based on what you have written, the string you format would be "ServerLinkGetUserById". That is different to the string you enter manually of #"ServerLink/GetUserById".
Try updating your format to be:
NSString* str = [NSString stringWithFormat:#"%#/%#",_mainURl,service];
NSString* str = [NSString stringWithFormat:#"%#/%#",_mainURl,service];
NSURL *url = [NSURL URLWithString:str];
don't you try like this ??
i think i am not sure exact what issue having you but as your bellow description, i think you left this part

How do I add a number to an NSURL? Too many arguments error

I've got a small problem that seems a little bit odd to me. I often used NSString or NSLog while adding NSNumbers into several places:
NSNumber *categoryId = [[NSNumber alloc]initWithInt:0];
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
Now xcode tells me that I'm too many arguments. What am I doing wrong? Setting up an NSNumber into NSStrings or NSLogs works as I did it above.
Best Regards
What is wrong is on
NSURL *url = [NSURL URLWithString:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
you are calling URLWithString: and then pass in a string that is not being formatted correctly. If you want to do it all on one line then you need to be using stringWithFormat: like
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]]];
Because it is adding a parameter you can't just create a string like you normally would with #"some text" you need to format it using the stringWithFormat: which will return an NSString * with the text held within #"" and the paramters you pass in. So [NSString stringWithFormat:#"My String will come with %#", #"Apples"]; this would provide an NSString with "My String will come with Apples". For more information check out the Apple Documentation for NSString and stringWithFormat:
Try this :
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://shop.rs/api/json.phpaction=getCategoryByCategory&category=%i", [categoryId integerValue]]];
Initially code was wrong because of : "categoryId integerValue]" (I forgot a '[').
You can use NSString to form your NSURL. You can then pass it to your URLWithString like below:
NSNumber *categoryId = [NSNumber numberWithInteger:0];
NSString *urlString = [NSString stringWithFormat:#"http://shop.rs/api/json.php?action=getCategoryByCategory&category=%i",[categoryId integerValue]];
NSURL *url = [NSURL URLWithString:urlString];

NSUrl fileURLWithPath returns strange chinese signs

I have an NSString path to my Documents folder.
NSString* stringURL = #"/var/mobile/Applications/5667FADC-F848-40CF-A309-
7BFE598AE6AB/Library/Application Support/MyAppDirectory";
When I cast it to NSUrl with
NSURL* url = [NSURL fileURLWithPath:stringUrl];
and NSLog(#"Created URL: %#",url);, i get some strange result:
///var/mobile/Applications/5667FADC-F848-40CF-A309-7BFE598AE6AB/Library/Application㤈㤋ތȀ乽啓汲唠䱒›楦敬⼺⼯慶⽲潭楢敬䄯灰楬慣楴湯⽳㘵㜶䅆䍄䘭㐸ⴸ〴䙃䄭〳ⴹ䈷䕆㤵䄸㙅䉁䰯扩慲祲䄯灰楬慣楴湯㈥匰灵潰瑲䴯䅹灰楄敲瑣牯⽹upport/MyAppDirectory/
Why is this so ?
What am I doing wrong ?
I didn't see any Chinese character when I log the value.
NSString* stringURL = #"/var/mobile/Applications/5667FADC-F848-40CF-A309-7BFE598AE6AB/Library/Application Support/MyAppDirectory";
NSURL* url = [NSURL fileURLWithPath:stringURL];
NSLog(#"%#",url);
Classical mistake. Don't use NSLog (url), use NSLog (#"%#", url). The first argument to NSLog is a format string, and % characters in format strings are interpreted, not printed. For example, %s in a format string means another C-String is expected in the argument list. Since url could contain all kinds of characters, this is likely to lead to rubbish results or even crashes.
Based on the answer you accepted from a previous question; it's because the use of stringByAddingPercentEscapesUsingEncoding will generate a printf-like formatting string containing %20S (the space between Application Support is converted to %20), which confuses NSLog():
NSURL *url = [NSURL fileURLWithString:[stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] isDirectory:YES];
NSLog(url);
use NSLog("#%", url) to avoid this error.

Data argument not used by format string but it works fine

I used this code from the Stack Overflow question: URLWithString: returns nil:
//localisationName is a arbitrary string here
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%#,Montréal,Communauté-Urbaine-de-Montréal,Québec,Canadae&output=csv&oe=utf8&sensor=false", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
When I copied it into my code, there wasn't any issue but when I modified it to use my url, I got this issue:
Data argument not used by format string.
But it works fine. In my project:
.h:
NSString *localisationName;
.m:
NSString* webName = [localisationName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
How can I solve this? Anything missing from my code?
The # in the original string is used as a placeholder where the value of webName is inserted. In your code, you have no such placeholder, so you are telling it to put webName into your string, but you aren't saying where.
If you don't want to insert webName into the string, then half your code is redundant. All you need is:
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";
NSString* webStringURL = [stringURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:webStringURL];
[_webView loadRequest:[NSURLRequest requestWithURL:url]];
The +stringWithFormat: method will return a string created by using a given format string as a template into which the remaining argument values are substituted. And in the first code block, %# will be replaced by value of webName.
In your modified version, the format parameter, which is #"http://en.wikipedia.org/wiki/Hősök_tere", does not contain any format specifiers, so
NSString* stringURL = [NSString stringWithFormat:#"http://en.wikipedia.org/wiki/Hősök_tere", webName];
just runs like this (with the warning Data argument not used by format string.):
NSString* stringURL = #"http://en.wikipedia.org/wiki/Hősök_tere";

URL for GET request

To get the JSON I was using this answer SBJsonWriter Nested NSDictionary
Now I have a sting {"key1":"bla1","key2":{"a":"a1","b":"b1","c":"c1","d":"d1"},"key3":"bla3"} that I've called theString
and I need to add it to a url http://mysyte.net:8888/JSON?
and to receive something like this http://lcwebtest.sytes.net:8888/JSON?{"key1":"bla1","key2":{"a":"a1","b":"b1","c":"c1","d":"d1"},"key3":"bla3"}
Here is what I do:
NSString *urlString = [NSString stringWithFormat:#"http://mysyte.net:8888/JSON?%#",theString];
NSLog gives http://mysyte.net:8888/JSON?{"key2":{"d":"d1","b":"b1","c":"c1","a":"a1"},"key1":"bla1","key3":"bla3"}
Then I make a url from it by
NSURL *url1 = [NSURL URLWithString:urlString];
BUT NSLog(#"%#",url1); gives me {null}
I assume NSURL does not want to read the "{" or "}" and thinks that the url was malformed.
How can I receive the url to make a GET request?
I assume NSURL does not want to read the "{" or "}" and thinks that the url was malformed.
That's right, you're not allowed to put some special characters in a URL. You want to escape the JSON string like this:
CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)theString, // (__bridge CFStringRef)theString if you use ARC
CFSTR(""),
CFSTR("?&=%,:+-"),
kCFStringEncodingUTF8
);
NSString *urlString = [NSString stringWithFormat:#"http://mysyte.net:8888/JSON?%#", (NSString *)escaped];
CFRelease(escaped);

Resources