我有一个连接到外部附件的项目,并与iOS应用程序之间进行少量数据通信。我可以像苹果在EADemo参考代码中那样设置会话和流,一切似乎都运行得很好。
我遇到的问题是,在随机使用应用程序一段时间后,输出流停止工作,但输入流仍然运行良好。在每次写入尝试之前,我都会检查以确保hasSpaceAvailable为真,并且当我读回写入的字节数时,一切看起来都是正确的。此外,查看run循环并没有显示工作和非工作之间的任何差异,流状态仍然显示为打开。
我能看到的唯一导致这种情况的是,我的附件没有连续确认几次应用程序的写入尝试,然后它就崩溃了。
我如何检测我处于这种状态,以及如何修复它?
// low level write method - write data to the accessory while there is space available and data to write
- (void)_writeData {
while (([[_session outputStream] hasSpaceAvailable]) && ([_dataToWrite length] > 0))
{
NSInteger bytesWritten = [[_session outputStream] write:[_dataToWrite bytes] maxLength:[_dataToWrite length]];
if (bytesWritten == -1)
{
NSLog(@"write error");
break;
}
else if (bytesWritten > 0)
{
[_dataToWrite replaceBytesInRange:NSMakeRange(0, bytesWritten) withBytes:NULL length:0];
}
}
}
// low level read method - read data while there is data and space available in the input buffer
- (void)_readData {
NSLog(@"reading data to buffer");
#define EAD_INPUT_BUFFER_SIZE 128
uint8_t buf[EAD_INPUT_BUFFER_SIZE];
while ([[_session inputStream] hasBytesAvailable])
{
NSInteger bytesRead = [[_session inputStream] read:buf maxLength:EAD_INPUT_BUFFER_SIZE];
if (_dataToRead == nil) {
_dataToRead = [[NSMutableData alloc] init];
}
[_dataToRead appendBytes:(void *)buf length:bytesRead];
}
[[NSNotificationCenter defaultCenter] postNotificationName:EASessionDataReceivedNotification object:self userInfo:nil];
}
// high level write data method
- (void)writeData:(NSData *)data
{
// NSLog(@"writing data to buffer");
if (_dataToWrite == nil) {
_dataToWrite = [[NSMutableData alloc] init];
}
[_dataToWrite appendData:data];
[self _writeData];
}
// high level read method
- (NSData *)readData:(NSUInteger)bytesToRead
{
NSLog(@"reading data");
NSData *data = nil;
if ([_dataToRead length] >= bytesToRead) {
NSRange range = NSMakeRange(0, bytesToRead);
data = [_dataToRead subdataWithRange:range];
[_dataToRead replaceBytesInRange:range withBytes:NULL length:0];
}
return data;
}
- (BOOL)openSession
{
NSLog(@"openSession");
[_accessory setDelegate:self];
if(_session){
[self closeSession];
}
_session = [[EASession alloc] initWithAccessory:_accessory forProtocol:_protocolString];
if (_session)
{
_runLoop = [NSRunLoop currentRunLoop];
[[_session inputStream] setDelegate:self];
[[_session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[_session inputStream] open];
[[_session outputStream] setDelegate:self];
[[_session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[_session outputStream] open];
NSLog(@"creating session succeeded!");
}
else
{
NSLog(@"creating session failed!");
}
return (_session != nil);
}发布于 2013-05-06 21:47:25
我想我可能也遇到了同样的问题。
但是,如何检测该问题是由附件无法确认数据引起的呢?
现在,我最好的办法是尝试检测应用程序中的情况。在我的情况下,我可以这样做,因为如果附件没有从电话接收到任何数据,它将重新发送相同的包。
https://stackoverflow.com/questions/16109686
复制相似问题