Subclassing NSInputStream to upload a particular portion of data from a local filepath

1.5k views Asked by At

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 ?

1

There are 1 answers

0
seb On

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