Handle invalid UTF-8


/ Published in: Objective C
Save to your folder(s)

Convert UTF-8 NSData to NSString without failing if UTF-8 is invalid. Instead, replace invalid characters with the replacement character (�). This requires some Omni frameworks. Use this as a replacement for NSString's initWithData:encoding: method.


Copy this code and paste it in your HTML
  1. // http://www.omnigroup.com/ftp/pub/software/Source/MacOSX/Frameworks/
  2. // Link with {OWF, OmniFoundation, OmniBase, OmniNetworking}
  3. // http://forums.omnigroup.com/showthread.php?t=1867
  4. #import <OWF/OWDataStream.h>
  5. #import <OWF/OWDataStreamCharacterCursor.h>
  6.  
  7. NSString* stringWithUTF8Data(NSData *data)
  8. {
  9. OWDataStream *dataStream = [[[OWDataStream alloc] initWithLength:[data length]] autorelease];
  10. [dataStream writeData:data];
  11. return OFMostlyApplyDeferredEncoding([[[[OWDataStreamCharacterCursor alloc] initForDataCursor:[dataStream newCursor] encoding:OFDeferredASCIISupersetStringEncoding] autorelease] readString], kCFStringEncodingUTF8);
  12. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.