Search code examples
objective-cbuffering

Objective-C: Read specific buffer size from URL


I need to download large files from a URL asynchronously and fill a buffer (for example 4096 bytes) to a specific size before processing the data. It would be great to use a built-in object such as NSURLConnection but I am having some problems.

With NSURLConnection, the didReceiveData:data message decides when to fire on its own. For example, I might receive 954 bytes the first time and subsequently 1048 bytes until it's done downloading. Is there anyway I can modify NSURLConnection to force it to read to the buffer size I need before firing the receive message?

I also looked into using the CFNetwork classes, but this seems alot more difficult and would like to avoid it if possible.

Additionally I might be able to accomplish this by using the well known AsyncSocket class, but then I'd have to parse HTTP headers and I have a feeling more issues would come up down the line with other web server configurations.

Thank you in advance.


Solution

  • With NSURLConnection you have to read the data into your own buffer anyway (e.g. an NSData object). So why not just read from that buffer every 4096 bytes?

    It sounds like you're only interested in processing the data as it arrives, and not in keeping all of it. So perhaps you could do something like this whenever you receive data (pseudocode):

    while buffer.size > 4096:
      copy first 4096 bytes into separate buffer
      process separate buffer
      delete first 4096 bytes from buffer
    

    And then process whatever is left (if necessary) when the connection closes.