4

I am having a 100 MB of data in a single file. This 100 mb data will be divided virtually. i.e., I need to create an NSInputStream which points to different 5MB chunks. This is possible by creating the stream with NSData.

But rather I'd like to know if I can have a NSInputStream which points to a range of data in the file ?

Sj.
  • 1,674
  • 2
  • 15
  • 23
  • Why not use `NSFileHandle` instead? – maroux May 03 '13 at 12:43
  • basically i dont want to create several NSData instances of size 5MB. it eats up a lot of memory. – Sj. May 03 '13 at 12:47
  • you should then create one part of 5MB at a time in some serial queue for instance – art-divin May 03 '13 at 12:50
  • And you shouldn't. Create a `NSFileHandle` and read the appropriate bytes at any offset by doing `seekToFileOffset:`. – maroux May 03 '13 at 12:52
  • Here ill be uploading a very long file from my iOS App. Im concurrently uploading different parts of the same file. Also there can be several file uploads also. If I create the Data with a filehandle this uploading will take around 30MB which I dont want. That is why i thought of going with NSInputStream. But with the NSInputStream I cannot offset the read buffer. Or the only solution will be writing each 5MB data to a file and create an InputStream from that File ?? – Sj. May 03 '13 at 13:02

1 Answers1

4

If you want to upload a file by passing a NSInputStream instance to NSURLRequest.HTTPBodyStream you indeed have to create a subclass of NSInputStream and only stream the bytes you want to upload. Using NSFileHandle is not an option here.

Creating a subclass of NSInputStream that works with NSURLRequest is quite tricky, but fortunately here is a great blog post about how it can be accomplished.

Here you can find a ready to use subclass of NSInputStream for this purpose.

You can feed ChunkInputStream with another NSInputStream reading a file and pass start position and number of bytes to read.

Swift example:

let fileInputStream = NSInputStream(fileAtPath: "/tmp/readme")
let inputStream = ChunkInputStream(inputStream: fileInputStream)
inputStream.startPosition = 2097152
inputStream.readMax = 1048576
seb
  • 2,350
  • 24
  • 30