Ios 如何从外部附件异步发送和接收数据

Ios 如何从外部附件异步发送和接收数据,ios,asynchronous,nsstream,external-accessory,iphone-accessory,Ios,Asynchronous,Nsstream,External Accessory,Iphone Accessory,我对从外部附件异步发送和接收数据的方式感到困惑。我使用MFi外部附件,我检查了EADemo,但似乎是发送和接收数据同步的方式。对此有任何建议,请提前感谢。首先,您必须将输入/输出流附加到runLoop: [[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [[session inputStream] open]; [[session outputStr

我对从外部附件异步发送和接收数据的方式感到困惑。我使用MFi外部附件,我检查了EADemo,但似乎是发送和接收数据同步的方式。对此有任何建议,请提前感谢。

首先,您必须将输入/输出流附加到runLoop:

[[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session inputStream] open];
[[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session outputStream] open];
成为他们的代表:

[[session outputStream] setDelegate:self];
[[session inputStream] setDelegate:self];
一旦您成为代理人,您必须实施此方法:

-(void)stream:handleEvent:{};
以下是一个例子:

-(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)_event {
    switch (_event)
    {
        case NSStreamEventHasBytesAvailable:
            /* This part will be executed every time your rx buffer contains at least 1 byte */
            switch(state) {
                uint8_t ch;
                /* Read byte per byte */
                [stream read:&ch maxLength:1];
                /* now ch contains a byte from your MFI device
                ** and 'read' function decrease the length of the rx buffer by -1 */
            }
            break;
    }
}
这是将数据写入流的命令:

/* txQueue is a NSData containing data to transmit. */
[[session outputStream] write:(uint8_t *)[txQueue bytes] maxLength:[txQueue length]];

我需要一个失败的回应。请帮帮我?