从NSData正确编码中文字符

时间:2013-08-26 09:35:50

标签: iphone ios encoding nsstring

请帮助我,我使用下面的代码来获取文件名。 在这里,我从NSString获得NSData,其中multipartDataNSMutableArray,其中包含NSData

NSString* postInfo = [[NSString alloc] initWithBytes:[[multipartData objectAtIndex:1] bytes] length:[[multipartData objectAtIndex:1] length] encoding:NSUTF8StringEncoding];

我得到的字符串如下:

Printing description of postInfo:

Content-Disposition: form-data; name="file"; filename="??:??.PNG"

但它应该是这样的:

Printing description of postInfo:

Content-Disposition: form-data; name="file"; filename="华语/華語.PNG"

提前致谢。

1 个答案:

答案 0 :(得分:0)

显然,服务器不使用UTF-8对响应进行编码,但可能是another Chinese-only encoding。您需要使用Content-Type标头来检测它是哪种编码,然后使用以下代码找到相应的NSStringEncoding;

// set charset to the MIME charset you get from the server
CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)(charset)));

这是一个详细的答案:

// getting the Content-Type header (e.g. "application/json; charset=utf-8")
NSString* header = [[response allHeaderFields] objectForKey:@"Content-Type"];

// getting the MIME type
NSString* charset = nil;
NSArray* contentTypeParts = [header componentsSeparatedByString:@";"];
NSInteger i = 0;
for (NSString* part in contentTypeParts) {
    // ignoring first loop (e.g. "application/json")
    if (i > 0) {
        NSArray* partComponents = [part componentsSeparatedByString:@"="];
        if ([partComponents count] == 2 && [@"charset" isEqualToString:[[partComponents objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]]) {
            charset = [[partComponents objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            break;
        }
    }
    i++;
}

// converting the MIME type to NSStringEncoding
NSStringEncoding stringEncoding = NSUTF8StringEncoding; // default to UTF8
if (charset) {
    stringEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)(charset)));
}

// finally you can convert your string properly!
NSString* postInfo = [[NSString alloc] initWithBytes:[[multipartData objectAtIndex:1] bytes] length:[[multipartData objectAtIndex:1] length] encoding:stringEncoding];