crax
crax

Reputation: 391

NSStreamEventEndEncountered not happen for NSInputStream when read content from file

I created a NSInputStream to load content from a file(IOS):

NSString* fileName = [[NSBundle mainBundle] pathForResource:@"resource" ofType:@".dat"];
NSInputStream* dataStream = [NSInputStream inputStreamWithFileAtPath:fileName];
if (dataStream == nil) {
    NSLog(@"load asset failed");
    return;
}

[dataStream setDelegate:self];
[dataStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                            forMode:NSDefaultRunLoopMode];
[dataStream open];

Then, add event handler:

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
    switch(eventCode) {
        case NSStreamEventEndEncountered: {
            [stream removeFromRunLoop:[NSRunLoop currentRunLoop]
                                       forMode:NSDefaultRunLoopMode];

            break;
        }
    }
}

I want to catch the event:NSStreamEventEndEncountered, but not happend. I can only catch NSStreamEventOpenCompleted and NSStreamEventHasBytesAvailable.

Anything wrong? Thanks for any help!

Upvotes: 2

Views: 3815

Answers (3)

James Bush
James Bush

Reputation: 1525

None of these answers are correct. To trigger the NSStreamEventEndEncountered event, you must attempt to read data from the input stream when there is no data to read (in other words, when the paired output stream stops writing data).

Upvotes: 0

Alex Zavatone
Alex Zavatone

Reputation: 4323

I just ran in to this. Replace NSStreamEventEndEncountered with 4 in the switch/case statement.

NSStreamEventEndEncountered as an NSStream enum doesn't end up being caught in a case statement.

Upvotes: 0

Matt
Matt

Reputation: 1563

I can't see anything wrong with the code you've posted. Make sure that when you're finished with the stream that you are closing it yourself rather than simply relying on getting an NSStreamEventEndEncountered notification, which you can do simply with something like this:

- (void) disconnect {
    // Close all open streams
    [inputStream close];
    [outputStream close];
}

You'll usually only get NSStreamEventEndEncountered if the connection is closed by the other end of the stream, which depending on what you're doing may be beyond your control.

Upvotes: 3

Related Questions