Escape characters in NSURLRequest - iphone

I'm trying to pass a request to a URL using HTTP POST on iPhone. The HTTP body contains some escape characters.
NSString *requestMessage=[NSString stringWithString:#"?username/u001password/u001description"];
NSMutableURLRequest *url=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://welcome.com"]];
[url setHTTPMethod:#"POST"];
[url setHTTPBody:[requestMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:url delegate:self];
The escape character here is /u001.
Using this code I don't get any correct responses. I think the trouble is with the escape characters only. Please give me a solution for how to give an escape sequence like this in Cocoa. Thanks in advance.

You've confused forward slashes (/) with backslashes (\). You need a backslash to form an escape sequence; a slash is just a slash, and “/u001” is just a slash, the letter u, two digits zero, and a digit one.
That said, if you actually want to include U+0001 in your string, even \u001 is wrong. You want \x01 or maybe \u0001 (but I seem to remember that GCC complains if you use \u for a character lower than U+0100).
I do wonder why the server would require U+0001 as the separator, though. Are there public API docs for whatever server you're querying?

What do you want to escape? I don't quite understand what you are trying to do. Do you want to write "&"? Then do it. It's not HTML.
Besides that, [NSString stringWithString:#"…constant string…"] is superfluid. #"…constant string…" is all you need.
There is a method in NSString to add percent-escapes to URLs: -(void)stringByAddingPercentEscapesUsingEncoding:. Maybe that's what you're looking for?

Related

Not able to pass special character into request

When I try to make request with some special character like japanese , then request is going to break and i am not able to get result. so my question is, how to pass special character in other language into request ?
Thanks in Advance.
You should encode your characters to UTF8 like this
NSString *encodedURL = [oldUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

encoding information in filenames (iPhone/mac)

I want to encode a short title in filenames. The problem is that occasionally the title will contain a character such as a colon or a slash. Is there a standard encoding that would be typical/appropriate for this?
EDIT: to clarify, I want to encode the title in such a way that the encoded title could be used as a filename. Or is that called percent escaping?
The way I do this is with a category on NSURL, which I use to get the NSURL for a filename in a particular directory. Once I have this NSURL, I can fetch or save the file using the URL after performing the usual checks about whether or not the file already exists and handling those cases accordingly.
The relevant code snippet is:
+ (NSURL *)adnURLForFileName:(NSString *)fileName inDirectory:(NSSearchPathDirectory)searchDirectory {
NSString *percentEscapedFileName = [fileName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSURL *URLForDirectory = [[fileManager URLsForDirectory:searchDirectory inDomains:NSUserDomainMask] objectAtIndex:0];
return [NSURL URLWithString:percentEscapedFileName relativeToURL:URLForDirectory];
}
You can download the full category code from GitHub - NSURL+ADNFileHelpers
You could use -stringByReplacingOccurrencesOfString:withString: to replace the slash character with U+2044, the "solidus" aka "fraction slash". It looks like this: ⁄
http://en.wikipedia.org/wiki/Solidus_(punctuation)
The slash is not allowed in the Unix APIs. The colon is not allowed in HFS and in the old File Manager APIs. The same filename character will show up as a colon in the former and as a slash in the latter. In practice: you can use the Finder to rename a file to "/" (because the Finder uses the traditional Mac separator of :), but it will show up as ":" if you use ls.
If you need to allow both colons and slashes, you need to encode the characters somehow. You could use URL-style escaping, but if you expect the user to look at the filename in the Finder or in some other program, it's going to look horrible. It's better to escape just the path separator. For example, if you're using the Unix style APIs (path separator /), you could encode / as :- and : as :: (to avoid ambiguity). Or you could use some other little-used character for the escape.
I have approached this problem by filtering the title before using it in the filename. NSString has some useful methods, such as stringByStandardizingPath and stringByReplacingOccurrencesOfString:withString:. The filtering approach is lossy, in that the original title information might not be restorable. Similarly, I don't think encoding would work because iOS allows such a wide range of characters in its filenames. One possible alternative solution could be a plist archive with key=filename, value=title.

how to write special character in objective-C NSString

when I try to write this JSON:
{"author":"mehdi","email":"email#hotmail.fr","message":"Hello"}
like this in Objective-C:
NSString *myJson=#"{"author":"mehdi","email":"email#hotmail.fr","message":"Hello"}";
it doesn't work. Can someone help me?
You need to escape quote characters with a backslash:
NSString *myJson = #"{\"author\":\"mehdi\",\"email\":\"email#hotmail.fr\",\"message\":\"Hello\"}";
Otherwise the compiler will think that your string literal ends right after the first {.
The backslashes will not be present as characters in the resulting NSString. They are merely there as hints for the compiler and are removed from the actual string during compilation.
Newbie note: JSON strings that you read directly from a file via Objective C of course do not need any escaping! (JSON itself may need such, but that's about it. No need for additional escaping on the ObjC-side of it.)

Newline chars somehow get added to my strings. And cant remove them

On some of my strings there seems to be somekind of newline char. I think this is the case because when i do a simple NSLog
NSLog(#"Test: %#",aNSMutableString);
I would get output like below
Test:
I am a String
I've tried using
[mutableString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
But it does not remove whatever it is thats forcing the newline to happen.
In a string that i parse out from a file which has 4 characters 'm3u8' has 5 chars when I check the length of the new string.
Anybody got an idea of what might be going on?
Thanks
-Code
P.S.
I know I could just zap the first char out of all my strings but it feels like a hack and i still wont know whats going on.
[mutableString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
The above will not directly modify your mutableString. It returns a new autoreleased NSString with the characters trimmed. See NSString doc.
e.x.
NSString *trimmedString = [mutableString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSLog(#"Test: %#", trimmedString);
should give you expected results.
I think #Sam 's answer will fix your problem, but I think the origin of your problem is the file source. Do you know how it is encoded? Is it part of a download? My guess is that you have a Windows' file with "\n\r" terminating lines and you are using Unix string tools that are breaking on "\n", thus leaving a leading "\r".
Verify the source of the file and read the document lines with the appropriate encoding.

Problem with RegExKitLite and ampersands

So I'm trying to rip URLs from an NSString using RegExKitLite and I came across an odd problem.
NSLog(#"Array: %#", [message componentsMatchedByRegex:#"^(http://)[-a-zA-Z0-9+&##/%?=~_()|!:,.;]*"]);
NSString *message is just some text with a URL within it. The strange thing is it doesn't work with the ampersand in it. If I take the ampersand out it works fine, but for obvious reasons I want to keep the ampersand in. I'm also a Regex newb, so don't bash my search expression to much :)
Anyone experience this before with RegExKitLite or RegEx in general in Objective-C?
In ICU regular expression character classes, & means intersection. For example #"[[:letter:] & [a-z]]". So it needs to be quoted as Peter suggestion, with a backslash, ie \& in the regular expression. However, \ has a special meaning in C strings, including Objective C strings. So the \ has to itself be quoted with . So you need \& in your pattern. Ie, [-a-zA-Z0-9+\&##/%?=~_()|!:,.;]
Also, I'm not sure what your intention is with the ^ at the start of the URL. If you want the regex to match anywhere in the string, you should use \b (word break) instead. If you want it to match URLs that are only at the start of the message, then you would only ever get a single match as written. If you want it to match URLs that are at the start of a line, then add (?m) at the start of the regex to turn on multiline matching for ^ (and consider adding $ to the end of the regex).
I've no experience with RegExKitLite, and never encountered & as special inside a character class, but try putting a \ before it to see if that works?
NSLog(#"Array: %#", [message componentsMatchedByRegex:#"^(http://)[-a-zA-Z0-9+\&##/%?=~_()|!:,.;]*"]);