2010-10-05 75 views
0

所以我有这样一段代码:重新编码的NSString返回null

if ([receivedPage hasPrefix:[NSString stringWithUTF8String:"\xC3\xAF\xC2\xBB\xC2\xBF"]]) // UTF-8 BOM 'EF BB BF' as UTF-16 chars 
    { 
     //DebugLog(@"converting calls list to UTF8"); 
     receivedPage = [[[NSString alloc] initWithData:[receivedPage dataUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] autorelease]; 
    } 

但是有时候当如果是真的receivedPage变为零。为什么会发生?

接收到的页面是这个函数的返回值:

NSURLResponse * response; 
    NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error]; 

    if ([result length] > 0) 
     return [[[NSString alloc] initWithBytes: (const void*)[result bytes] length:[result length] encoding: encoding] autorelease]; 
    else 
    { 
     if (error && *error) 
      DebugLog(@"URL request got error: %@",*error); 
     return nil; 
    } 

这里的编码NSISOLatin1StringEncoding(不知道为什么,我调试别人的代码)。

任何想法为什么会发生这种情况?

回答

0

它看起来像你试图把字符串(包含字符的对象)当作数据(包含字节的对象)。保留从连接收到的数据,并检查其中的UTF-8 BOM(正确的三字节版本),然后根据您是否找到它,使用NSUTF8StringEncodingNSISOLatin1StringEncoding

或者,只要有条件地使用UTF-8,如果您可以修复服务器来做到这一点。

此外,您应该切换此代码以异步使用NSURLConnection。如果用户的互联网连接速度很慢,则会将您的应用程序挂在此处。以异步方式进行操作可让您保持UI的运行,并在适当的时候显示进度,并使用户可以取消。