I am downloading a file and writing its bytes to an NSOutputStream:
self.outputFileStream = [NSOutputStream outputStreamToFileAtPath:downloadFilePath
append:NO];
[self.outputFileStream setDelegate:self];
Then, in a NSURLSession's didReceiveResponse callback:
[self.outputFileStream open];
And, once the first bytes received:
const uint8_t *bytes = (const uint8_t*)[data bytes];
NSInteger bytesLeft = [data length];
NSInteger bytesWritten = -1;
do {
bytesWritten = [self.outputFileStream write:bytes maxLength:bytesLeft];
if (bytesWritten == -1) {
break;
}
bytesLeft -= bytesWritten;
} while (bytesLeft > 0);
The execution stops the first time I try to write data to the stream: write:maxLength: returns -1.
To find out why this is happening, I have implemented a delegate method handleEvent: eventCode:.
For some reason, it only gets called if I place the following lines of code when initializing the stream:
[self.outputFileStream scheduleInRunLoop:[NSRunLoop mainRunLoop]
forMode:NSDefaultRunLoopMode];
and returns NSStreamEventErrorOccurred with No such file or directory description, although the directory is double-checked to be existing.