gpt4 book ai didi

ios - 检测到不正确的 NSStringEncoding 值 0x0000。假设 NSASCIIStringEncoding

转载 作者:行者123 更新时间:2023-11-28 22:11:06 25 4
gpt4 key购买 nike

我在使用这段代码时遇到了这个错误:

    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"];

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

最佳答案

这段代码很糟糕。

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

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

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

关于ios - 检测到不正确的 NSStringEncoding 值 0x0000。假设 NSASCIIStringEncoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com