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

时间:2012-10-23 08:33:24

标签: ios asynchronous nsstream external-accessory iphone-accessory

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

1 个答案:

答案 0 :(得分:2)

首先,您必须将输入/输出流附加到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]];