【问题标题】:Incorrect NSStringEncoding value 0x0000 detected. Assuming NSASCIIStringEncoding检测到不正确的 NSStringEncoding 值 0x0000。假设 NSASCIIStringEncoding
【发布时间】:2014-04-06 21:51:14
【问题描述】:

我收到此代码的错误:

    NSMutableURLRequest *request = [ [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL_LOGIN_API]] autorelease];
    [request setHTTPMethod:@"POST"];

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];

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

    NSString *responseData=[[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];

 ...
     NSDictionary *dictionary  = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:nil] options:NSJSONReadingMutableContainers error:&e];

用新代码编辑:

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSError *e = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:urlData options: NSJSONReadingMutableContainers error: &e];
NSString *response_code = [[dictionary objectForKey:@"data"] valueForKey:@"response"];

我也在使用同步请求。在这里使用异步请求有什么好处? 另外,更新代码很困难,所以我将使用异步请求?

【问题讨论】:

  • 您检查 urlData 是否为空?或者 NSURLConnection 是否有任何错误?
  • 是的。但它现在可以工作了,我将 NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:nil] options:NSJSONReadingMutableContainers error:&e] 替换为 NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];需要添加默认编码

标签: ios objective-c nsurlconnection nsmutableurlrequest


【解决方案1】:

这段代码很糟糕。

您正在获取响应数据并使用 ASCII 编码将其转换为字符串。好吧,那是垃圾,因为如果您的响应中有任何 Unicode 字符,它将失败。

然后你把字符串变成一个 NSData 对象并传递一个字符串编码为 nil。编译器会抱怨吗?我打赌确实如此。你应该在这里传递一个编码。同样,如果您不使用 Unicode 编码,如果您有一个包含 Unicode 字符的字符串,这将无法创建任何数据。

整个双重转换是无稽之谈,因为 NSJSONSerialization 需要 NSData,而您的原始响应是 NSData,所以您所做的就是获取响应并按原样给它 NSJSONSerialization,节省大量内存,大量 CPU 时间,并且它完全避免了您引入的双重错误。

【讨论】:

  • 感谢您的评论。你能检查我的新编辑并告诉我它是否看起来更好吗?
  • @Aymenworks - 您应该检查 nil 返回值,如果出现,记录 error 值。
【解决方案2】:

当您在主线程(即 UI 线程)上运行时,异步请求非常有用。同步请求可能会导致您的 UI 在请求“正在播放”时释放。

对于异步请求,您将异步接收数据。当接收到数据时,调用(委托协议的)方法并在那里处理接收到的数据。

【讨论】:

  • 将“可能导致您的 UI 冻结”替换为“将使您的 UI 冻结并让所有用户讨厌您”:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多