1

How can I check to see if an NSString contains base64 data in an if statement? Because base64 encodes the data in a completely random way, I can't search for a phrase within the NSString so instead I will need to check to see if the contents of the string results in a data file.

objc-obsessive
  • 775
  • 1
  • 11
  • 17
  • 1
    to check if a string is base64 encoded http://stackoverflow.com/questions/8571501/how-to-check-whether-the-string-is-base64-encoded-or-not reads promising. – Kai Huppmann Apr 25 '12 at 16:56
  • You can't check, with 100% reliability. All you can do is see if it MIGHT be base64. (And it's a poor design where you would not know from some other source whether the data is base64 or not.) – Hot Licks Apr 25 '12 at 17:38

1 Answers1

5

Here's a category on NSString I created that should work:

@interface NSString (MDBase64Additions)
- (BOOL)isBase64Data;
@end

@implementation NSString (MDBase64Additions)

- (BOOL)isBase64Data {
    if ([self length] % 4 == 0) {
        static NSCharacterSet *invertedBase64CharacterSet = nil;
        if (invertedBase64CharacterSet == nil) {
            invertedBase64CharacterSet = [[[NSCharacterSet
               characterSetWithCharactersInString:
        @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="]
                                     invertedSet] retain];
        }
        return [self rangeOfCharacterFromSet:invertedBase64CharacterSet
           options:NSLiteralSearch].location == NSNotFound;
    }
    return NO;
}

@end

If you expect newlines or blank spaces in the data, you could update this method to remove those first (likely NSCharacterSet's +whitespaceCharacterSet).

If there's primarily just one class where you'll be using this category method, you could put this code inside its .m file above that class's @implementation block. If you think you might want to use that category from more than one class, you could create a separate .h & .m pair to contain it (e.g. MDFoundationAdditions.h, MDFoundationAdditions.m), and then import it into those classes.

To use:

NSString *dataString = /* assume exists */;

if ([dataString isBase64Data]) {

}
NSGod
  • 21,896
  • 3
  • 51
  • 63
  • thanks for this. Would I create a .m file with the first bit of code in then import it? – objc-obsessive Apr 25 '12 at 18:10
  • This is not working for me, BOOL result1 = [self isBase64Data:@"Rayan"]; BOOL result2 = [self isBase64Data:@"Khan"]; for result 1 it returns NO and for result2 it return YES. – Bharat Modi Nov 08 '16 at 09:43