NSURLRequest with HTTPBody input stream: Stream se

2019-03-22 06:37发布

问题:

I want to send a large amount of data to a server using NSURLConnection (and NSURLRequest). For this I create a bound pair of NSStreams (using CFStreamCreateBoundPair(...)). Then I pass the input stream to the NSURLRequest (-setHTTPBodyStream:) and schedule the output stream on the current run loop. When the run loop continues, I get the events to send data and the input stream sends this data to the server.

My problem is, that this only works when the data fits into the buffer between the paired streams. If the data is bigger, then somehow the input stream gets an event (I assume "bytes available") but the NSURLConnection has not yet opened the input stream. This results in an error message printed and the data is not being sent.

I tried to catch this in my -stream:handleEvent: method by simply returning if the input stream is not yet opened, but then my output stream gets a stream closed event (probably because I never sent data when I could).

So my question is: How to use a bound pair of streams with NSURLConnection correctly?

(If this matters: I'm developing on the iOS platform)

Any help is appreciated!

Cheers, Markus

回答1:

Ok, I kind of fixed this by starting the upload delayed, so that it starts after the NSURLConnection had time to setup its input stream.

It's not what I call a clean solution though, since relying on -performSelector:withObject:afterDelay: seems a bit hacky.

So if anyone else has a solution to this, I'm still open for any suggestions.