0

I want to write binary data to a file and add that as an email attachment.

  MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
  picker.mailComposeDelegate = self;
  NSData *data = [[self.samples componentsJoinedByString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding];
  [picker addAttachmentData:data mimeType:@"application/octet-stream" fileName:filename];

addAttachmentData expects an NSData * to be passed (although I'd prefer a byte array). samples is an NSMutableArray *. I'm getting extra formatting in the file that I do NOT want however, like angle brackets and whitespace:

...
<17700000 16c0f710 c78a2660 1570f960 c78926>
<17710060 17d0f800 c98826d0 2160f990 cb8d26>
...

Where are these coming from? How can I truly write just binary data?

0

1 Answer 1

4

Calm down. NSData is a byte array — no more, no less. What you're seeing is just a figment of what the logging process does. Try this:

NSArray <NSString*>* arr = @[@"Mannie", @"Moe", @"Jack"];
NSData *data = 
    [[arr componentsJoinedByString:@"\n"] dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", data);

The console outputs:

<4d616e6e 69650a4d 6f650a4a 61636b>

It's just NSLog making things neater. The bytes are just the 2-digit hex number values; there are no angle brackets and spaces in the data.

If you really don't believe me, print it this way:

char buffer[100];
[data getBytes:buffer length:data.length];
for (NSUInteger i = 0; i < data.length; i++) {
    NSLog(@"%02x", buffer[i]);
}

The output is just the character bytes:

4d
61
6e
6e
69
65
0a
4d
6f
65
0a
4a
61
63
6b
Sign up to request clarification or add additional context in comments.

2 Comments

Wow you have an incredible reputation matt. Hmm, I'm reading the sent attachment as a binary file in python and am seeing 0x3C = 60 = '<' as the initial byte. When I open the file in sublime, I see the same thing.
Okay, but now you've sort of changed the question, haven't you? It seemed to me that question was "What are these extra things in my NSData?" And I showed you how to prove to yourself there are no extra things. How an octet stream is represented in an email is another matter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.