问题
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.
回答1:
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]) {
}
来源:https://stackoverflow.com/questions/10320186/checking-if-an-nsstring-contains-base64-data