iOS - Serialize JSON with arabic NSString - iphone

I'm in quite a pickle, I'm acquiring user input in Arabic which is stored in a NSString.
The string is displayed properly both in the app and the debug window.
Here's my problem: the string is added to a NSMutableDictionary then serialized to JSON
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
The data is then POSTed to the server, but the once Arabic content is represented as ????
This is obviously an encoding issue. I can't find the proper method to encode my NSString with UTF-8 and still add it to the Dictionary.
AddingPercentEncoding will encode it as URL UTF-8 encoding which is not what I'm after.
The only reasonable encoding I find is [NSString UTF8String] which turns the string to const char * that is not an NSObject.
What I'm really after is: مرحبا UTF-8 ---> Ùرحبا
The decoding works perfectly, if the iOS app receives JSON with such representation, the resulting NSDictionary will hold a key that returns the proper value in Arabic.
Thank you for your help! :D

Related

NSUrlRequest itself adding %0 in url

The NSURLRequest is adding %0 in request. I created the string and converted it into base 64 then send to url, but NSURLRequest is automatically adding %0 in it. Below is the code i am using.
This is how converted to base 64.
NSData *plainTextData = [totalStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
NSLog(#"encoded url:%#",base64String);
When Api called.
NSString *urlStr = [NSString stringWithFormat:#"http://mabct.co/api/checkin/%#", [code valueForKey:#"code"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:urlStr]];
// [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSString *responseString = [MyEventApi sendRequest:request];
NSError *error;
NSData *jsonData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"dict in API-------------%#",results);
return results;
This is the converted string in to base 64
eyJldmVudElkIjoiNDAiLCJzZWF0IjoiMTBfS2FyYW4gU3VraGlqYV8yNC0wNC0yMDEzIDE3OjE3IiwidXNlcklkIjoiMTAifQ==
This is what NSURLRequest is sending.
eyJldmVudElkIjoiNDAiLCJzZWF0IjoiMTBfS2FyYW4gU3VraGlqYV8yNC0wNC0y%0D%0AMDEzIDE3OjE3IiwidXNlcklkIjoiMTAifQ==
This is what i am sending in encoding
"{"eventId":"47","seat":"10_Karan Makhija_24-04-2013 10:06","userId":"10"}"
I am not getting what is wrong, please guide for the above.
Thanks in advance.
I see that %0D%0A is being added to your original string. I googled it and found that:
%0D%0A is the encoded ASCII non-printable characters of ,
which on Microsoft platforms is a NewLine So:
Consider if you accidentally could have replaced some HTML by hitting the return key while editing your files.
2a. Be aware of what
encoding your editor uses for saving the files (typically either
ASCII, ANSI, or Unicode)
2b. Your webserver (an IIS6, likely running
on a Windows 2003 Server) serves the files as UTF-8 encoded, which is
fine - But you may want to verify that it actually reads the files
using same encoding as you've used for saving the files.
Here, is the SOURCE if you want to check.
EDIT
Make sure that your webserver and client uses the same encoding (i.e. NSUTF8StringEncoding or any other, but same)
Also, IF base 64 encoding is there on web server. Follow this link, for implementing category for such encoding/decoding. I hope this will help you.

objective c string encoding issue

My app receives some data from server which is in XML format and some tags contains Japanese words. When I tried to execute the link in the browser, it gets the correct response in Japanese. For example:
<root>
<categorylist>
<cid>19</cid>
<cname>ファミリー</cname>
<lang>jap</lang>
</categorylist>
</root>
..but in my app, the response string is in some encoded format like the following:
<root>
<categorylist>
<cid>19</cid>
<cname>ファミリー</cname>
<lang>jap</lang>
</categorylist>
</root>
My code to receive XML from the server is:
NSString *req=#"http://www.myserver.com/category.php?lang=jap";
NSString *resultString=[NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:nil];
Is there a problem with my code? How can I convert the response to correct Japanese strings?
Try looking at some of the decoding methods listed on this question: HTML character decoding in Objective-C / Cocoa Touch

AFNetworking: encoding URL strings containing '%'-sign fails

I'm using AFNetworking in my iOS App. I've discovered a problem that occurs when request parameters contain percent signs. Then the encoding fails. The method AFURLEncodedStringFromStringWithEncoding returns nil.
I've tested this code and it prints (null):
NSLog(#"%#", AFURLEncodedStringFromStringWithEncoding(#"%", NSUTF8StringEncoding));
The expected output should be: %25. Other characters can be encoded with no problem.
The method is defined as follows:
NSString * AFURLEncodedStringFromStringWithEncoding(NSString *string, NSStringEncoding encoding) {
static NSString * const kAFLegalCharactersToBeEscaped = #"?!##$^&%*+,:;='\"`<>()[]{}/\\|~ ";
// Following the suggestion in documentation for `CFURLCreateStringByAddingPercentEscapes` to "pre-process" URL strings (using stringByReplacingPercentEscapesUsingEncoding) with unpredictable sequences that may already contain percent escapes.
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[string stringByReplacingPercentEscapesUsingEncoding:encoding], NULL, (CFStringRef)kAFLegalCharactersToBeEscaped, CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];
}
Any ideas what's going wrong here?
EDIT: The issue has been fixed in AFNetworking.
I don't know about the API but URL encoding is normally done by
UTF-8 encoding the string portions--path, arguments, etc--into bytes
applying percent-encoding of the byte values to obtain ASCII-only string pieces
assembling the URL pieces together with the separators :, /, ?, & etc.
encoding that string into bytes again
sending it over the wire
See https://www.rfc-editor.org/rfc/rfc3986#section-2.5 for nuances. Note that the RFC states that if the URL refers to a document on an EBCDIC system, the URL should specify the byte values for the EBCDIC encoding of its name, not the string name that human users of the EBCDIC system know it by. So a URL is ultimately a byte-string not a character-string.
As to how to get your API to represent that byte-string correctly, I am unsure.
Just removing the stringByReplacingPercentEscapesUsingEncoding:encoding is fine, no need to encode twice, so the return value should be:
return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
NULL,
(CFStringRef)kAFLegalCharactersToBeEscaped,
CFStringConvertNSStringEncodingToEncoding(encoding)) autorelease];

iPhone NSURLConnection: What to do with returned NSData Object? Google Docs API

I'm working with the Google Docs API in my iPhone application. I've sent the proper POST request, and received a response along with some NSData. If I NSLog the NSData object, I get this:
NSData *returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:theResponse error:NULL];
NSLog(#"%#",returnedData);
//output : <4572726f 723d4261 64417574 68656e74 69636174 696f6e0a>
I think the NSData is either an NSDictionary or an NSArray. I'm supposed to receive a couple of items back, an SID, an LSID, and an Auth.
If I could turn the NSData chunk into an NSDictionary I could just find the object for whichever key.
Can anyone help?
You will have to decode the data. Try the following:
NSString *result= [[NSString alloc] initWithData:returnedData encoding:NSASCIIStringEncoding];
Of course this will depend on how the data is encoded. NSUTF8StringEncoding might work instead.
You may just need to pass the data to an NSXMLParser
The best way to deal with web data is Doing NSXML parsing. No need of decoding data the parser will handle itself

NSXMLParser init with XML in NSString format

I just ran into this one and couldn't seem to get any clear answer from the documentation.
Im retrieving some XML through a HTTPS connection. I do all sorts of authentication etc. so I have a set of classes that deals with this in a nice threaded way.
The result is an NSString that goes something like:
<response>
//some XML formatted test
</response>
This means that there is no encoding="UTF-8" indent="yes" method="xml" or other header blocks to indicate that this is actual XML and not just an NSString.
I guess I will use [NSXMLParser initWithData:NSData] to construct the parser, but how will I format or cast my NSString of xml formatted text into a proper NSData object that NSXMLParser will understand and parse?
Hope it makes sense, thank you for any help given :)
You can convert a string to a NSData object using the dataUsingEncoding method:
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
You can then feed this to NSXMLParser.
The headers are optional, but you can insert the appropriate headers yourself if needed:
NSString *header = #"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
NSString *xml = [NSString stringWithFormat:#"%#\n%#", header, response);
NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *praser = [NSXMLParser initWithData:data];
By the time NSXMLParser has the data it's pretty much going to be expecting it to be XML ;-)
I'm pretty sure the processing instruction header is optional in this context. The way you get the NSString into the NSData is going to dictate the encoding (using dataUsingEncoding:).
(edit: I was looking for the encoding enum, but Philippe Leybaert beat me to it, but to repeat it here anyway, something like: [nsString dataUsingEncoding:NSUTF8StringEncoding])
I've passed NSStrings of XML in this way before with no issues.
Not specific to this question as such, but on the subject of XML parsing in an iPhone context in general you may find this blog entry of mine interesting, too.