ios - 如何异步发送和接收来自外部配件的数据

标签 ios asynchronous nsstream external-accessory iphone-accessory

我对以异步方式从外部附件发送和接收数据感到困惑。我使用 MFi External Accessory,我检查了 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];

一旦你成为委托(delegate)人,你必须实现这个方法:

-(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]];

关于ios - 如何异步发送和接收来自外部配件的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13026392/

相关文章:

c# - 任务中的异步套接字操作

swift - 如何在 Swift 的 NSNetService 上使用 getInputStream()?

objective-c - 如何在 CCSprite 或 CCNode、Cocos2d 中更新 gamehud

java - 适用于 Android、iOS 和黑莓的 Codenameone 应用内计费

iOS 自动使用自定义阿拉伯语/西里尔语字体

ios - AVPlayer,播放/暂停状态通知?

Javascript 作用域、内联函数和异步操作

java - 亚马逊 sqs 的异步消费者

reference - [NSStream scheduleInRunLoop : forMode:] retain the NSStream? 是否

iphone - 简单的Iphone客户端连接到服务器