AaoIi
AaoIi

Reputation: 8396

initWithBase64Encoding deprecated base64

I am receiving a warning in Xcode after upgrading to Xcode 7 in my project, I'm using CoacoSecurity which uses Base64 for encryption in the following line of code :

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

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

}

Its telling me that initWithBase64Encoding is deprecated, so how can i get over this warning and fix it.

I've converted it but I'm getting another warning:

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

The warning says:

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

Upvotes: 2

Views: 920

Answers (3)

Volomike
Volomike

Reputation: 24906

Here's a solution that works with OSX 10.8 and up.

// 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];

I threw in the sResult line only if you wanted to convert it to an NSString instead of an NSData.

So, that gives you a Base64 encoded string. If you want to now unencode it, you would do:

// 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];
}

Upvotes: 2

AaoIi
AaoIi

Reputation: 8396

Well, first i used initWithBase64Encoding as @Ske57 recommended and then to get over that warning i had to cast it to NSDataBase64DecodingOptions and it should work fine :

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

Upvotes: 1

ske57
ske57

Reputation: 607

use this

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

instand of

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

Upvotes: 2

Related Questions