NSURLConnection receives data even if no data was thrown back

Posted by Anna Fortuna on Stack Overflow See other posts from Stack Overflow or by Anna Fortuna
Published on 2012-10-04T09:35:28Z Indexed on 2012/10/04 9:37 UTC
Read the original article Hit count: 277

Let me explain my situation. Currently, I am experimenting long-polling using NSURLConnection. I found this and I decided to try it. What I do is send a request to the server with a timeout interval of 300 secs. (or 5 mins.)

Here is a code snippet:

NSURL *url = [NSURL URLWithString:urlString];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowedInMemoryOnly timeoutInterval:300];

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];

Now I want to test if the connection will "hold" the request if no data was thrown back from the server, so what I did was this:

if (data != nil)
    [self performSelectorOnMainThread:@selector(dataReceived:) withObject:data waitUntilDone:YES];

And the function dataReceived: looks like this:

- (void)dataReceived:(NSData *)data
{
   NSLog(@"DATA RECEIVED!");
   NSString *string = [NSString stringWithUTF8String:[data bytes]];
   NSLog(@"THE DATA: %@", string);
}

Server-side, I created a function that will return a data once it fits the arguments and returns none if nothing fits. Here is a snippet of the PHP function:

function retrieveMessages($vardata)
{
if (!empty($vardata))
{
        $result = check_data($vardata)
        //check_data is the function which returns 1 if $vardata 
        //fits the arguments, and 0 if it fails to fit 

        if ($result == 1)
        {
           $jsonArray = array('Data' => $vardata);
           echo json_encode($jsonArray);
        }
}
}

As you can see, the function will only return data if the $result is equal to 1. However, even if the function returns nothing, NSURLConnection will still perform the function dataReceived: meaning the NSURLConnection still receives data, albeit an empty one. So can anyone help me here? How will I perform long-polling using NSURLConnection?

Basically, I want to maintain the connection as long as no data is returned. So how will I do it?

NOTE:

I am new to PHP, so if my code is wrong, please point it out so I can correct it.

© Stack Overflow or respective owner

Related posts about php

Related posts about objective-c