简体   繁体   English

IOS上的字符串编码issuse

[英]A string encoding issuse on IOS

I came across a problem with string encoding in ios development. 我在ios开发中遇到了字符串编码问题。 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: 我用中文创建了一些值,然后为这些值创建了一个NSDictionary,该字典用作网络请求的参数:

在此处输入图片说明

- (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. 将字典转换为JSON形式,作为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: 最后,使用上面的字符串创建了完整的URL:

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”进行网络请求,并设置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. 所有数据已成功发送到服务器,但是当我从服务器请求这些数据并在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. 我已经仔细检查了应该编码或解码字符串的所有位置,仅使用utf8。 What`s more , for the server side , no other encoding used either. 而且,对于服务器端,也没有使用其他编码。 And my colleague has tested sent data from Android platform, no problem. 我的同事已经测试了从Android平台发送的数据,没问题。 So I think maybe I have missed some points. 所以我想也许我错过了一些要点。

Any advise? 有什么建议吗?

By using the class Base64 you can encode or decode the string. 通过使用Base64类,您可以对字符串进行编码或解码。

Add Base64 class in your project from HERE 这里在您的项目中添加Base64类

see the mehode in class to encode. 参见类中的编码方法。

Encode: 编码:

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

- (NSString *)base64EncodedString;

Decode: 解码:

- (NSString *)base64DecodedString;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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