The input and output streams get opened all the time and the respective delegate methods get called with the correct NSStreamEvent code (NSStreamEventOpenCompleted). However, on some openSession attempts the streams get opened successfully but they don't work. Sometimes I can only write to the output stream but I can't read from the input stream. Sometimes I can't read or write.
Has anyone has ever ran into this problem or have any idea to why this is happening? Any help is appreciated. Thanks.
Here is some relevant code
- (BOOL)openSession
{
_session = [[EASession alloc] initWithAccessory:_selectedAccessory
forProtocol:_protocolString];
if (!_session)
return false;
[_selectedAccessory setDelegate:self];
[[_session inputStream] setDelegate:self];
[[_session outputStream] setDelegate:self];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
[[_session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[[_session inputStream] open];
[[_session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[[_session outputStream] open];
[[NSRunLoop currentRunLoop] run];
});
return true;
}
- (void)setupControllerForAccessory:(EAAccessory *)accessory withProtocolString:(NSString *)protocolString
{
_selectedAccessory = accessory;
_protocolString = [protocolString copy];
}
/**
* There is something weird happening here too, this always get called twice when an accessory
* gets connected. Once without a protocol string and once with a protocol string. I just
* ignore the one without a protocol string.
*/
- (void)accessoryConnected:(NSNotification *)notification
{
EAAccessory *connectedEA = [notification.userInfo objectForKey:@"EAAccessoryKey"];
// Check to see if the connected EA has a protocol string
if ([[connectedEA protocolStrings] count] == 0)
return;
[self setupControllerForAccessory:connectedEA
withProtocolString:[[connectedEA protocolStrings] objectAtIndex:0]];
[self openSession];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventOpenCompleted:
// This case always gets called twice, once for input and once for output
NSLog(@"stream %@ opened", aStream);
break;
case NSStreamEventHasBytesAvailable:
break;
case NSStreamEventHasSpaceAvailable:
break;
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
[self closeSession];
break;
default:
break;
}
}
- (void)closeSession
{
[[_session inputStream] close];
[[_session inputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[_session inputStream] setDelegate:nil];
[[_session outputStream] close];
[[_session outputStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[_session outputStream] setDelegate:nil];
_session = nil;
_selectedAccessory = nil;
_protocolString = nil;
}