lehn0058
lehn0058

Reputation: 20237

How to handle chunking while streaming JSON data to NSURLConnection

I have a web server that is streaming JSON results back asynchronously to an iOS client. The client is connecting using NSURLConnection and I access the data from the method:

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData)

Data is currently coming back in 1024 byte chunks. However, I'm not sure how to tell if when I receive data if the message was complete other than appending all the data I receive to a string and try to parse it to JSON each time. This method seems quite error prone - is there a better way to handle this? Something that would mark in the headers or something when a full response has been sent?

Upvotes: 1

Views: 1437

Answers (2)

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

You have two ways

first & better way is implement connectionDidFinishLoading: NSURLConnectionDataDelegate delegate which will trigger when a connection has finished loading successfully.

Second way is handling it manually as follows.

You can do the following things in Web-server side,

Step1: Send the below informations first before starting to send the original data.

      a.Number of Chunks.[totalSize/1024] (mandatory).
      b.TotalSize(not mandatory).

You can do the following things in Client side side,

Step1: Store the above informations.

Step2: Write the below code

@property (nonatomic,assign) int chunkNumber;

@property (nonatomic,strong) NSData *receivedData;

Self.chunkNumber = 1;

    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData)myata{

       if(self.chunkNumber != Number of Chunks)
       {
          if(!self.receivedData)
          {
            //allocate and initialize self.receivedData
          }

          [self.receivedData appendData:myData];    

       }
       else
       {

         //completed . do whatever with self.receivedData.
         //if you want to validate, just check the self.receivedData size with TotalSize

        self.chunkNumber = 1;

       }

    }

Upvotes: 2

DrC
DrC

Reputation: 7698

In the NSURLConnectionDataDelegate, there is a method connectionDidFinishLoading: that should be called when the server is done sending. You can also retrieve the expected length in didReceiveResponse but that is not reliable and required server side support.

Upvotes: 1

Related Questions