0

How can I read a string from a text input in objective C (iOS SDK), and treating it as UTF-16, encode the bytes to base64?

I'm struggling with both aspects, both treating the textbox's value as UTF-16 and then encoding these bytes to UTF-16.

I appreciate there are probably partial or similar questions to this on SO, I have searched (and read the various posts), but I'm an iOS/objective C noob and could really benefit from a complete example here.

Thanks

Andrew Bullock
  • 36,616
  • 34
  • 155
  • 231

2 Answers2

4

Convert the NSString to a UTF16-encoded NSData by using

[str dataUsingEncoding:NSUTF16StringEncoding]

then convert the resulting NSData into Base64 using e.g. the answer from Converting between NSData and base64 strings.

Community
  • 1
  • 1
nneonneo
  • 171,345
  • 36
  • 312
  • 383
0

Assuming you know how to get the value as an NSString* (which should be pretty simple), you can get UTF-16 using -getCharacters:range::

unichar *buffer = malloc(sizeof(unichar) * [str length]);
[str getCharacters:buffer range:NSMakeRange(0, [str length])];

This will give you a unichar* buffer, which is a buffer of UTF-16 characters.

Alternatively, if you prefer working with NSData*, you can use

[str dataUsingEncoding:NSUTF16StringEncoding];
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347