使用Apple的External Accessories API捕获数据流

时间:2012-12-03 07:26:54

标签: objective-c ios iostream

您好我正在为iPAD制作应用程序,其中我必须捕获来自外部设备的数据,该设备每秒发送512个值。我使用了Apple的外部附件API,并且代码如下: -

- (void)stream:(NSStream*)theStream handleEvent:(NSStreamEvent)streamEvent  
{  
    switch (streamEvent)  
 {  
   case NSStreamEventNone:  //Sent when open complete
  //NSLog(@"NSStreamEventNone");
   break;   
  case NSStreamEventOpenCompleted:  //Sent when open complete

  //NSLog(@"NStreamEventOpenCompleted: %@", theStream);
  break ;

  case NSStreamEventHasBytesAvailable:
    {
   //NSLog(@"NSStreamEventHasBytesAvailable");

    uint8_t buffer[1024];
    unsigned int len=0;

    len=[(NSInputStream *)theStream  read:buffer maxLength:1024];
    if(len>0){      

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

    NSString *value = [[NSString alloc] initWithData:dataencoding:NSASCIIStringEncoding];

   }
    }
 break;   

 case NSStreamEventHasSpaceAvailable:  
    os = theStream;
    break;
 case NSStreamEventErrorOccurred:  
   //NSLog(@"NSStreamEventErrorOccurred");
    break;   

  case NSStreamEventEndEncountered:  
    ////NSLog(@"NSStreamEventEndEncountered");
    break;   
  default:  
    break;  
  }  
 }

我从中获得的是一些没有正确编码的乱码文本。我也试过使用下面的内容: -

 NSString *value = [[NSString alloc] initWithData:dataencoding:NSUTF8StringEncoding];

但这只是保持返回null。 编辑: - 当我在NSLog时,我得到以下内容: -

 vªª€ÿù…ªª€ ÿûƒªª€ÿK3ªª€ÿ£Ûªª€ÿ˳ªª€ÿ}ªª€ÿ噪ª€

我应该在这里得到整数。有人可以告诉我这里我做错了什么。

2 个答案:

答案 0 :(得分:3)

您的NSLog似乎是一串扩展的ASCII字符。假设它们来自Apple扩展的Ascii字符集,那么您列出的代码段开头所代表的uint8_t(1字节)数据是:

¬Ä√ø√π¬Ö¬™¬™¬A...

表示为十进制,这是:

172,196,26,248,26,192,172,214,172,34,172 ...

这是你的数据吗?这是一些测试输出的代码。

NSString *receivedString = @"€ÿù…ªª€"; // Change this to the string variable you were using with NSLog

for (int i=0; i<[receivedString length]; i++) 
{
    unsigned char asciiCode = [ receivedString characterAtIndex:i];
    NSLog( @"Value at %d is %d", i, asciiCode ); 
}

答案 1 :(得分:0)

您收到的数据是原始值。绝对肯定他们不是UTF8字符。很可能你必须直接从NSData的字节中将每2个字节放入一个2字节的整数。