@interfaceNSData (Base64)
/**
* @brief 字符串base64后转data
*/
+ (NSData*)dataWithBase64EncodedString:(NSString*)string
{
if(![string length])returnnil;
NSData *decoded =nil;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
if(![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)])
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
decoded = [[selfalloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]"withString:@""options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];
#pragma clang diagnostic pop
}
else
#endif
{
decoded = [[selfalloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
}
return[decoded length]? decoded:nil;
}
/**
* @brief NSData转string
* @param wrapWidth 换行长度 76 64
*/
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
if(![selflength])returnnil;
NSString *encoded =nil;
#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
if(![NSData instancesRespondToSelector:@selector(base64EncodedStringWithOptions:)])
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
encoded = [selfbase64Encoding];
#pragma clang diagnostic pop
}
else
#endif
{
switch(wrapWidth)
{
case64:
{
return[selfbase64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
case76:
{
return[selfbase64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
}
default:
{
encoded = [selfbase64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
}
}
}
if(!wrapWidth || wrapWidth >= [encoded length])
{
returnencoded;
}
wrapWidth = (wrapWidth /4) *4;
NSMutableString *result = [NSMutableString string];
for(NSUInteger i =0; i < [encoded length]; i+= wrapWidth)
{
if(i + wrapWidth >= [encoded length])
{
[result appendString:[encoded substringFromIndex:i]];
break;
}
[result appendString:[encoded substringWithRange:NSMakeRange(i, wrapWidth)]];
[result appendString:@"\r\n"];
}
returnresult;
}
/**
* @brief NSData转string 换行长度默认64
*/
- (NSString *)base64EncodedString
{
return[selfbase64EncodedStringWithWrapWidth:0];
}