initWithBase64Encoding不推荐使用base64

时间:2015-11-07 10:56:30

标签: ios objective-c encoding

我在项目中升级到Xcode 7后在Xcode中收到警告,我正在使用CoacoSecurity在以下代码行中使用Base64进行加密:

if (![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)])
{

    decoded = [[self alloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];

}

它告诉我initWithBase64Encoding已弃用,所以我该如何克服此警告并修复它。

我转换了它,但我又收到了警告:

decoded = [[self alloc] initWithBase64EncodedString:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@""] options:NSRegularExpressionSearch];

警告说:

Implicit conversion from enumeration type enum NSStringCompareOptions to different enumeration type NSDataBase64DecodingOptions (aka enum NSDataBase64DecodingOptions)

3 个答案:

答案 0 :(得分:2)

使用此

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];

NSData *data=[[NSData alloc]initWithBase64Encoding:(NSString *)dict];

答案 1 :(得分:2)

这是一个适用于OSX 10.8及更高版本的解决方案。

// assume sData is an NSString that's already been set
NSData *vData;
if ([vData respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
  vData = [[NSData alloc] initWithBase64EncodedString:sData options:kNilOptions];
} else { // 10.8 or earlier
  vData = [[NSData alloc] initWithBase64Encoding:sData];
}
NSString *sResult = [[NSString alloc]
            initWithData:vData encoding:NSUTF8StringEncoding];

只有当你想将它转换为NSString而不是NSData时,我才会进入sResult行。

因此,它为您提供了Base64编码的字符串。如果您现在要取消编码,您可以这样做:

// assuming sData is an NSString that's already been set
NSString *sResult = @"";
NSData *vData = [sData dataUsingEncoding:NSUTF8StringEncoding];
if ([vData respondsToSelector:@selector(base64EncodedStringWithOptions:)]) {
    sResult = [vData base64EncodedStringWithOptions:kNilOptions];
} else { // 10.8 or earlier
    sResult = [vData base64Encoding];
}

答案 2 :(得分:1)

好吧,首先我使用initWithBase64Encoding作为@Ske57推荐,然后为了克服警告我必须将其投放到NSDataBase64DecodingOptions,它应该可以正常工作:

decoded = [[self alloc] initWithBase64EncodedString:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@""] options:(NSDataBase64DecodingOptions)NSRegularExpressionSearch];