2015-11-07 34 views
2

我收到在Xcode警告在我的項目升級到Xcode中7,我用CoacoSecurity它採用Base64加密在下面的代碼行後:initWithBase64Encoding棄用的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]; 

警告說:

​​
+1

爲什麼你不去過時的方法的文檔?它告訴你要使用什麼。 –

回答

2

使用這種

instand的

NSData *data=[[NSData alloc]initWithBase64Encoding:(NSString *)dict]; 
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; 

1

嗯,首先我用initWithBase64Encoding@Ske57建議,然後拿到過該警告我不得不將它轉換爲NSDataBase64DecodingOptions,它應該很好地工作:

decoded = [[self alloc] initWithBase64EncodedString:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@""] options:(NSDataBase64DecodingOptions)NSRegularExpressionSearch]; 
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]; 

我在sResult線扔只有當你想將它轉換成一個NSString,而不是一個NSData。

所以,這給你一個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]; 
}