1

I am sending a request to a server in the following way:

- (void) getData
{
    NSString *url=  @"http://example.com";

    NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                     timeoutInterval:10.0];

exampleConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];

}

And for this the response is a JSON file, which I am parsing as follows:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Connection did finish loading %@",[connection currentRequest]);

    NSDictionary *exampleDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options: NSJSONReadingAllowFragments error:nil];

    NSLog(@"%@", exampleDictionary); // which gives me null

}

The response worked fine earlier. But now it gives me a null, which is obviously because something is hindering the conversion from JSON to NSDictionary. I investigated and found that the problem was because there were a couple of foreign characters (Chinese or something), at which the parsing process was going wrong.

I am not sure how to solve this problem. Does anyone have any ideas?

Rameez Hussain
  • 6,414
  • 10
  • 56
  • 85

1 Answers1

1

I played around with the classes and encoding options and ended up doing the following, which solved the problem.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSLog(@"Connection did finish loading %@",[connection currentRequest]);

    NSString *res = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];

    NSDictionary *exampleDictionary = [NSJSONSerialization JSONObjectWithData:[res dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingAllowFragments error:nil];

    NSLog(@"%@", exampleDictionary); // gives the actual data! :)

}
Rameez Hussain
  • 6,414
  • 10
  • 56
  • 85
  • I don't know if this a temporary workaround or the actual solution, but it works. :) – Rameez Hussain Mar 19 '13 at 16:29
  • Since you did not show any data or error message, nobody can decide if this is the correct solution or not. – Martin R Mar 19 '13 at 16:32
  • What is "received Data"? – Alioo Oct 17 '13 at 19:38
  • It's an NSMutableData object which you should initialise in your class and which will receive the data returned from your request. This is an old question and though it still is one of the correct ways to send HTTP GET requests, I have since migrated to AFHTTPNetworking 2.0. A lot simpler to use and understand. – Rameez Hussain Oct 17 '13 at 22:14