0

I'm looking at Apple's EADemo project, showing users how to use the External Accessory Framework. Could someone tell me how to display or "cout" the data received instead of just incrementing the number of bytes received? (I'm brand new to objective-c, ios, and all things apple!)

- (void)_sessionDataReceived:(NSNotification *)notification
{
    EADSessionController *sessionController = (EADSessionController *)[notification object];
    uint32_t bytesAvailable = 0;

    while ((bytesAvailable = [sessionController readBytesAvailable]) > 0) {
        NSData *data = [sessionController readData:bytesAvailable];
        if (data) {
            _totalBytesRead += bytesAvailable;
        }
    }

    [_receivedBytesLabel setText:[NSString stringWithFormat:@"Bytes Received from Session: %d", _totalBytesRead]];
}

And how would I change that last line to display the ascii data received instead of bytes received?

Thanks!

Jay Kim
  • 843
  • 4
  • 12
  • 28

2 Answers2

1

Just make an NSString from the data:

if (data) {
    _totalBytesRead += bytesAvailable;
    NSString *asciiStringFromData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    NSLog(@"ASCII bytes read: %@", asciiStringFromData);
}

If you need a different encoding, here's the list.

yuji
  • 16,695
  • 4
  • 63
  • 64
  • if i wanted the app to display the character instead of sending it to nslog, how would i change the last line to display the ascii instead of bytes received? – Jay Kim Apr 02 '12 at 19:39
  • i also get a warning that "class methond: '+initWithData:encoding:'(return type defaults to 'id')" – Jay Kim Apr 02 '12 at 19:45
  • My mistake, see updated code for a version that won't have that error. Displaying the string read from data instead of the number of bytes is not just a matter of changing the last line, since multiple strings could be read in the while loop. You need to accumulate all these strings using `NSString`'s `stringByAppendingString:` method, and then use that string instead of `_totalBytesRead`. And also change the `%d` to a `%@`. – yuji Apr 02 '12 at 19:51
0

You need to convert NSData to NSString Convert UTF-8 encoded NSData to NSString You can then print out the NSString like this:

NSLog(@"the data I got was %@", myString);

This assumes myString is what you created from the NSData.

Community
  • 1
  • 1
rooftop
  • 3,031
  • 1
  • 22
  • 33