1

我正在尝试通过 NSStream 每秒发送 UIImages

但是我在解码时崩溃了

NSData * data = [NSData dataWithBytes:buffer length:len];

*未捕获的异常:*** -[NSKeyedUnarchiver initForReadingWithData:]:无法理解的存档(0x62、0x70、0x6c、0x69、0x73、0x74、0x30、0x30)*

由于处理不当,数据看起来已损坏/不完整

- 我不确定我是否应该创建一个新的流,每次我想发送一个图像

- 我不确定解码,尤其是缓冲区大小(以及如何通过设置大小变量使其工作)

// 每秒发送一个 UIImage

- (void)sendStreamImage:(UIImage *)image withOrientation:(UIInterfaceOrientation)orientation {

    NSError * error;
    NSOutputStream *outputStream = [self.session startStreamWithName:@"SnapClapStream" toPeer:[self.session.connectedPeers firstObject] error:&error];
    // handle error if present

    outputStream.delegate = self;
    [outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream open];

    NSData * imageData = ...
    NSDictionary * dictionary = @{@"imageData":imageData, @"orientation":@(orientation)};
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
    [outputStream write:[data bytes] maxLength:[data length]];
}

在流委托中

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {

    if (eventCode == NSStreamEventHasBytesAvailable) {

        if (![aStream isKindOfClass:[NSInputStream class]]) {
            return;
        }

        NSInputStream * inputStream = (NSInputStream *)aStream;

        NSInteger bufferSizeNumber = (25 * 1024);
        NSMutableData *myBuffer = [NSMutableData dataWithLength:bufferSizeNumber];

        uint8_t *buffer = [myBuffer mutableBytes];
        NSInteger len = 0;

        while ([inputStream hasBytesAvailable]) {
            len = [inputStream read:buffer maxLength:bufferSizeNumber];
            if (len > 0) {

                NSData * data = [NSData dataWithBytes:buffer length:len];
                NSDictionary * dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
                dictionary = [self processReceivedDictionary:dictionary];

                // thats it, dictionary should contain all the data

            }
        }

    } else if (eventCode == NSStreamEventEndEncountered) {

        ...

    }

}
4

0 回答 0