NSURLConnection gets a NULL value from server though response data is not NULL - iOS

836 views Asked by At

In my app I am establishing a connection with the server and try getting a JSON data from the server. When I sent the request, within moments a JSON object is generated in the server and it is sent back to the client (app). But the issue is 2 times out of 10 times, I am getting NULL value in the client even though the data is sent from the server ( not a NULL data but aJSONdata sinceJSON` data will be generated for all request).

I am not sure why I am getting NULL even though the data is generated in the server (By observing the server logs, I can say that)

The code is below

if(netStatus==ReachableViaWiFi || netStatus==ReachableViaWWAN){
    NSURL *url = [NSURL URLWithString:formattedURL];
    NSURLRequest* request = [NSURLRequest requestWithURL: url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
     {
         if (error){

         }
         else{
             if ([NSString stringWithUTF8String:[jsonData bytes]]==NULL){
NSLog("The result is NULL");    
}

I am getting The result is NULL sometimes. I am not able to find a pattern. But this occurs 2 out of 10 times. I am not able to localise whether the issue is with the server or the app. Kindly let me know. Thanks for your time

1

There are 1 answers

2
Wain On BEST ANSWER

If using initWithData:encoding: to create the string works then it is just an issue with your logging. Indeed, you could check the data length rather than trying to decode the text. Even better would be to use NSJSONSerialization with the data directly, supplying appropriate options and logging the resulting object and error.