简体   繁体   中英

A string encoding issuse on IOS

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:

在此处输入图片说明

- (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:

在此处输入图片说明

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM