简体   繁体   中英

Incorrect NSStringEncoding value 0x0000 detected. Assuming NSASCIIStringEncoding

I'm getting this error with this code :

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

Edit with new code :

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

Also i'm using synchronousRequest. What are the advantage to use an asynchronous request here ? Also, it's difficult to update the code So I will be using an asynchronous request ?

This code is awful.

You are taking the response data and turning it in a string using ASCII encoding. Well, that is rubbish, because if there are any Unicode characters in your response, it will fail.

Then you turn the string into an NSData object and pass a string encoding of nil. Does the compiler complain about it? I bet it does. You are supposed to pass an encoding here. Again, if you don't use a Unicode encoding, this will fail to create any data if you have a string with Unicode characters.

And the whole double conversion is nonsense, because NSJSONSerialization wants NSData, and your original response was NSData, so all you do is take the response and give it NSJSONSerialization as it is, saving tons of memory, tons of CPU time, and it completely avoids the double bug that you introduced.

Asynchrnous requests are advangageous when you'd run on the main thread, wich is the UI thread. Sync requests might cause your UI to freese while the request is "on the air".

For async requests you will receive the data asynchronously. When the data is received a method (of a delegate protocol) is called and there you process the data received.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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