Encoding spaces in UITextView / UITextField to URL format - iphone

I'm trying to send the contents of UITextView or UITextField as parameters to a php file
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",nameField.text, tagsField.text, dreamEntry.text];
When i log urlstr, the url format is ok just as long as the UITextView or UITextField don't contain spaces. How would i go about converting the spaces to %20 ?
edit
here is the code at present, which not only crashes but isn't encoding the url properly.
name=John Doe&tags=recurring nightmare&entry=Testing testing testing
is converted to
name=John -1844684964oe&tags=recurringightmare&entry=Testing 4.214929e-307sting -1.992836e+00sting
- (IBAction)sendButtonPressed:(id)sender
{
NSString *urlString = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#", nameField.text, tagsField.text, dreamEntry.text];
NSString *encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:encodedString];
NSLog(encodedString);
NSLog(urlString);
[urlString release];
[url release];
[encodedString release];
}

Actually, all of the previous answers contain at least some inaccuracies, which for many common values of user provided text in the TextFields would not correctly communicate with the server
stringByAddingPercentEscapesUsingEncoding: percent escapes all characters which are not valid URL characters. This method should applied once to the entire URL.
A previous answer claims that stringByAddingPercentEscapesUsingEncoding: works like the URL building classes in many scripting languages, where you should not apply it to the entire URL string, but it doesn't. Anyone can easily verify this by checking its output for unescaped &s and ?s. So it is fine to apply to the entire string, but it is not enough to apply to your 'dynamic' url content.
The previous answer is right in that you have to do some more work to the names and values that go into your CGI query string. Since CGI is specified by RFC3875, this is often referred to as RFC3875 percent escaping. It makes sure that your names and values don't contain characters that are valid URL characters but which are significant in other parts of the URL (;, ?, :, #, &, =, $, +, {, }, <, >, and ,)
However, it is very important to also finish by doing plain URL percent escapes on the full string to make sure that all characters in the string are valid URL characters. While you don't in your example, in general there could be characters in a 'static' part of the string which are not valid URL characters, so you do need to escape those as well.
Unfortunately, NSString doesn't give us the power to escape the RFC3875 significant characters so we have to dip down into CFString to do so. Obviously using CFString is a pain so I generally add a Category onto NSString like so:
#interface NSString (RFC3875)
- (NSString *)stringByAddingRFC3875PercentEscapesUsingEncoding:(NSStringEncoding)encoding;
#end
#implementation NSString (RFC3875)
- (NSString *)stringByAddingRFC3875PercentEscapesUsingEncoding:(NSStringEncoding)encoding {
CFStringEncoding cfEncoding = CFStringConvertNSStringEncodingToEncoding(encoding);
NSString *rfcEscaped = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#";/?:#&=$+{}<>,",
cfEncoding);
return [rfcEscaped autorelease];
}
#end
With this Category in place, the original problem could be correctly solved with the following:
NSString *urlEscapedBase = [#"http://server.com/file.php" stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedName = [nameField.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedTags = [tagsField.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *rfcEscapedEntry = [dreamEntry.text stringByAddingRFC3875PercentEscapesUsingEncoding:
NSUTF8StringEncoding];
NSString *urlStr = [NSString stringWithFormat:#"%#?name=%#&tags=%#&entry=%#",
urlEscapedBase,
rfcEscapedName,
rfcEscapedTags,
rfcEscapedEntry];
NSURL *url = [NSURL URLWithString:urlStr];
This is a little variable heavy just be more clear. Also note that the variable list provided to stringWithFormat: should not be nil terminated. The format string describes the precise number of variables that should follow it. Also, technically the strings for query string names (name, tags, entry,..) should be run through stringByAddingPercentEscapesUsingEncoding: as a matter of course but in this small example we can easily see that they contain no invalid URL characters.
To see why the previous solutions are incorrect, imagine that the user input text in dreamEntry.text contains an &, which is not unlikely. With the previous solutions, all text following that character would be lost by the time the server got that text, since the unescaped ampersand would be interpreted by the server as ending the value portion of that query string pair.

You're not supposed to URL-escape the entire string, you're supposed to URL-escape the dynamic components. Try
NSString *urlStr = [NSString stringWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",
[nameField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[tagsField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[dreamEntry.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
nil];
NSURL *url = [NSURL URLWithString:urlStr];
The second issue with your code (and undoubtedly the reason for the odd printing) is you're passing the string directly to NSLog, so it's being treated as a format string. You need to use
NSLog(#"%#", encodedString);
instead. That will make it print as expected.
Edit: A third issue with your code is you're mixing autoreleased and owned objects, then releasing them all at the end. Go look at the 3 objects you create, and which you subsequently release later. One of them shouldn't be released later because it was produced by a method that did not start with the words alloc, copy, or new. Identifying the object in question is an exercise left to the reader.

You can take your URL and use:
NSString *urlStr = [[NSString alloc] initWithFormat:#"http://server.com/file.php?name=%#&tags=%#&entry=%#",nameField.text, tagsField.text, dreamEntry.text];
NSString *encStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Related

How to encode URL in objective c xcode?

I'm doing this to encode my URL in this way,
but its not working,
i got the result in NSLog but its the same url nothing is changing.
Please help me to sort this issue.
below is my code :
NSString *unencodedUrlString =
[#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#" %#", unencodedUrlString);
Thanks in advance
The comma is a legal URL character, therefore stringByAddingPercentEscapesUsingEncoding leaves "2,7" as it is and does not replace it by "2%2C7".
If you want the comma to be replaced by a percent escape (as I understand from your
comment to the question), you can use CFURLCreateStringByAddingPercentEscapes
instead:
NSString *str = #"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7";
NSString *encoded = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)(str), NULL, CFSTR(","), kCFStringEncodingUTF8));
NSLog(#"%#", encoded);
Output:
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
The fourth parameter CFSTR(",") specifies that the comma should be replaced by
a percent escape even if it is a legal URL character.
Use this
NSString *str = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2,7"];
NSString *path = [str stringByReplacingOccurrencesOfString:#"," withString:#"/"];
NSLog(#"%#",path);
This will do nothing but will make , to /.

ios - NSString losing content when used in NSUrl

I have the following code - note it has to objects with temp, but I will explain.
NSString *temp = _passedOnURL;
NSString *temp = #"http://google.com"; //I comment the one out that I do not use.
NSLog(#"TEMP - %#", temp);
NSURL *feedURL = [NSURL URLWithString:temp];
NSLog(#"FEED URL - %#", feedURL);
The _passedOnURL is a string with the contents passed from a Segue.
Now when I use the 1st temp, the FEED URL returns (null), but when I Log Temp it is still there, so somehow the NSURL does not read the string.
When I hardcode the string with the second temp - there is no issue.
In my mind there is no difference for the NSURL when it is reading the NSString yet, it seems to behave different.
Is there any reason for this??
EDIT
When I do the following code I have no issues:
_passedOnURL = #"http://www.google.com";
so I really have no explanation for this???
try escaping it : [NSURL URLWithString: [temp stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]]
It seems you have an invalid url string stored in temp. Not every string can be converted to a url but the valid url. Invalid chars and format will lead a nil object after +URLWithString:. So would you let us know what is stored in temp when you try this?
According to the doc for URLWithString:
Parameters
URLString
The string with which to initialize the NSURL object. Must be a URL
that conforms to RFC 2396. This method parses URLString according to
RFCs 1738 and 1808.
Return Value
An NSURL object initialized with URLString. If the string was
malformed, returns nil.
So my guess is that your _passedOnURL is not a valid URL.
I would do a NSLog on your _passedOnURL to check if you are getting the string correctly from the other segue.

The different way to obtain URL

In order to obtain URL, I usually follow this way.
NSString *userText = urlText.text;
NSURL *url = [NSURL URLWithString:userText];
Of coursely, urlText is linked with UITextField.
However, Recently, I saw this code in audioStreaming program.
(This is the program.)
NSString *escapedValue =
[(NSString *)CFURLCreateStringByAddingPercentEscapes(nil, (CFStringRef)downloadSourceField.text, NULL, NULL,
kCFStringEncodingUTF8) autorelease];
NSURL *url = [NSURL URLWithString:escapedValue];
downloadSourceField is linked with UITextField.
What is diffence between these two methodes?
When I replaced the second method (escapedValue = ~~~ ) with (escapedValue = downloadSourceField.text;), the program worked well.
Could you let me know what is difference?
And What is the best method to obtain URL for streaming?
The second method will percent-escape some characters which are typically not allowed in URLs. As an example, the space character is not allowed and will be encoded as %20. NSURL does not support passing a string containing a non-allowed character which has not been escaped to +URLWithString:, therefore passing the string through CFURLCreateStringByAddingPercentEscapes first will let you support such URLs.
interesting,
however, digging in the NSString docs you find these two functions:
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
I think those are the "official" way of doing this

Spaces in a NSURL with variables doesn't load

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 will put the code here now, or else it won't make as much sense.
I am putting down what I need, this code does not work right now, and I will get to why later
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMMM"];
NSString *monthString = [formatter stringFromDate:date];
NSLog(#"MONTH STRING %#", monthString);
NSString *baseURLStr = #"http://www.mysite.ca/example";
NSURL *url = [NSURL URLWithString:[baseURLStr stringByAppendingFormat:#"announcements%20%#%20%d%20carson.ashx", monthString]];
[webView loadRequest:[NSURLRequest requestWithURL:url]];
[NSCalendar release];
So, this is where the problem lies... Encoded (HTML): stringByAppendingFormat:#"announcements%#%20%d%20example.ashx", monthString, day]];
Decoded it looks like this
stringByAppendingFormat:#"announcements %# %d example.ashx"]];
That should be easier to understand..
When I run with the %20's, it says "The requested document was not found"
When I run with spaces (" ") it is just white, and nothing loads.
I know the URL is correct, and if I take the variables out, it is the exact same problem, but when I move the %20's back to the baseURLStr, it works and loads just fine, so it is something to do with the HTML Codes and the "stringbyAppendingFormat" string.
Any help is appreciated!
Thanks for your time
-Kyle
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 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"]
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.

Parsing NSStrings to ensure a correctly formed JSON string within XCode

I am reading string data from a PLIST which I am using to create a JSON string (incidentally for use within Facebook Connect).
NSString *eventLink = [eventDictionary objectForKey:EVENT_FIND_OUT_MORE_KEY];
NSString *eventLinkEscaped = [eventLink stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *eventName = [eventDictionary objectForKey:EVENT_NAME_KEY];
NSString *eventDescription = [eventDictionary objectForKey:#"Description"];
NSString *eventImageAddress = [eventDictionary valueForKey:#"Image URL"];
if ([eventImageAddress length] == 0)
{
eventImageAddress = NO_EVENT_IMAGE_URL;
}
// Publish a story to the feed using the feed dialog
FBStreamDialog *facebookStreamDialog = [[[FBStreamDialog alloc] init] autorelease];
facebookStreamDialog.delegate = self;
facebookStreamDialog.userMessagePrompt = #"Publish to Facebook";
facebookStreamDialog.attachment =[NSString stringWithFormat: #"{\"name\":\"%#\",\"href\":\"%#\",\"description\":\"%#\",\"media\":[{\"type\":\"image\",\"src\":\"%#\",\"href\":\"%#\"}]}", eventName, eventLinkEscaped, eventDescription, eventImageAddress, eventLinkEscaped];
[facebookStreamDialog show];
All this works well, but certain event descriptions (4 out of approx. 150) the text that appears in the dialog is blank. I have found the obvious candidates, i.e., the description contains the " character for instance or the copyright symbol. My question is, is there an easy method call, such as stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding that will ensure that any dodgy characters are escaped or ignored?
Thanks in advance,
Dave
I don't think there is an easy way to escape the problem strings. If you need JSON support anywhere else in your code, consider using one of the existing JSON parsing/generator frameworks such as yajl-objc or SBJSON. Either of these will let you build your response as Foundation objects (NSArray/NSDictionary) and then call a single method to generate the appropriate JSON. Your code will be cleaner and you have the benefit that both of these frameworks are well-tested.
If just need to generate this one bit of JSON, your best bet is probably to manually walk over the input strings, replacing potential problem characters with the appropriately escaped versions. Is is not as bad as you might think. Take a look at the source for SBJsonWriter