2

I came across a problem with string encoding in ios development. The story is as below:

I create some values in Chinese and then create a NSDictionary for those values, the dictionary is used as parameter for network request:

enter image description here

- (void)createActivity
{
    NSString *actionTheme = titleF.text;
    NSString *actionTitle = biaotiF.text;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:actionTheme, @"actionTheme", actionTitle, @"actionTitle",nil];
    [self networkrequest:];
}

Then some work has been done for the dictionary:

Transform the dictionary to the form of JSON as the type of NSString.

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 

Encoding the string , because of Chinese word in the string.

NSString *urlEncodedString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

At last a full url was create with the string above:

http://app.ic100.com/action/add?paramJson=%7B%22actionTheme%22%3A%22%E6%88%96%E8%80%85%E5%92%8C%E7%94%9F%E6%B4%BB%22%2C%22actionSite%22%3A%22%E5%8E%A (something like this)

I use the third party "ASIFormDataRequest" for network request, and I also set the StringEncoding:

ASIFormDataRequest *requstHttp  = [[ASIFormDataRequest alloc] init];
[requstHttp setStringEncoding:NSUTF8StringEncoding];
....

All the datas has been sent to the server successfully, but when I request these data from the server and show then on the iphone. It turn to be unreadable text:

enter image description here

I have carefully checked all the place that I should encode or decode the string, and only utf8 is used. What`s more , for the server side , no other encoding used either. And my colleague has tested sent data from Android platform, no problem. So I think maybe I have missed some points.

Any advise?

itenyh
  • 1,921
  • 2
  • 23
  • 38
  • It's not clear to me why you are url-encoding the JSON string. Also if you have issues with reading data from the server, show *that* code, not the code that sends data. – Droppy Oct 16 '14 at 06:58

1 Answers1

0

By using the class Base64 you can encode or decode the string.

Add Base64 class in your project from HERE

see the mehode in class to encode.

Encode:

+ (NSString *)stringWithBase64EncodedString:(NSString *)string;

- (NSString *)base64EncodedString;

Decode:

- (NSString *)base64DecodedString;
Kirit Modi
  • 23,155
  • 15
  • 89
  • 112
  • Why do you need a category at all, when all the real implementation is already in `NSData`? It might be more convenient, but it's certainly not necessary. – Droppy Oct 16 '14 at 06:56
  • So what value does your answer add? What has base-64 got to do with the issue in the first place? – Droppy Oct 16 '14 at 07:00