I'm trying to stream data between two iOS NSURLConenctions (one downloading, the other uploading), but can't seem to make it work.
- I have two NSURLConnections running simultaneously.
- One is downloading content from a url using a GET request.
- The other is uploading the same content just received, to another url, in the request body of a PUT request.
- In the upload connection I'm using setHTTPBodyStream to specify a custom NSInputStream whose read method returns data previously received from the other connection.
- Both NSURLConnections are scheduled in the run loops of separate background threads, so that any (possibly blocking) delegate callbacks don't mess with each other (and neither with the main thread).
So I thought it would work like this:
- The upload connection calls [read:maxLength] (which I have overridden) on the input stream.
- Since there's no data available yet, the read call blocks.
- On another thread, [connection:didReceiveData:] is called on the delegate of the download connection.
- It puts the received data in a shared buffer, thus making it available for the input stream of the upload connection.
- The upload stream's read call now isn't blocked anymore, it can return a chunk of data.
Unfortunately in practice, this does not work. After the upload stream's read method blocks, the download connection's delegate methods (eg. didReceiveData) don't get called anymore. (Note that if I disable the blocking on the upload side, then didReceiveData on the download side does get called all right.)
I suspect that this has to do something with the fact that the upload input stream's read method is called not on the thread where the connection and the stream objects were created, but on some other thread (apparently created by Cocoa). As if this was some shared thread used by both NSURLConnections, so once it's blocked, all other connections stop working as well. Or something like that.
Does anyone have an idea about what's really happening?
Also, is there a way to control on which thread the request body input stream's read method gets called?