Checking if an NSString contains base64 data

雨燕双飞 提交于 2020-01-23 03:22:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!