简体   繁体   English

在NSData和base64字符串之间转换

[英]Converting between NSData and base64 strings

What is the easiest and fastest code to do a conversion between NSData and a base64 string? NSData和base64字符串之间进行转换的最简单,最快的代码是什么? I've read a bunch of solutions at SO and mostly they involve in adding another class etc. I found a great solution here but it's too complex. 我在SO上阅读了一堆解决方案,大多数都涉及添加另一个类等。我在这里找到了一个很好的解决方案但它太复杂了。

Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files . 向下滚动到您链接的页面上的结论部分,然后下载提供的NSData + Base64文件 Its the best solution I have seen so far and is incredibly easy to use. 它是迄今为止我见过的最好的解决方案,非常容易使用。 If you can learn anything about Cocoa, you can learn to use that project. 如果您可以了解有关Cocoa的任何信息,您可以学习使用该项目。


Example

NSString *originalString = [NSString stringWithFormat:@"test"]; 
NSData *data = [NSData dataFromBase64String:originalString];  
NSLog([data base64EncodedString]); 

The above will print out the original string after converting it to base64 and back to a normal unencoded string. 以上将在将其转换为base64并返回到正常的未编码字符串后打印出原始字符串。

As of iOS 7, NSData now directly provides this functionality with the new methods -base64EncodedDataWithOptions: and -base64EncodedStringWithOptions: . 从iOS 7开始, NSData现在直接使用新方法-base64EncodedDataWithOptions:-base64EncodedStringWithOptions:提供此功能。 (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.) (这些选项允许您指定字符串是/应该是换行的,更好地处理电子邮件和面向用户的显示。)

You don't need any custom implementation. 您不需要任何自定义实现。 Creating base64 from NSData is shown in other answers. 从NSData创建base64将在其他答案中显示。 There is opposite direction. 有相反的方向。 From Base64 string to NSData: 从Base64字符串到NSData:

 NSString *base64Encoded = @"some base64 string";
 NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];

I ended up using this same class as provided by SUDZC 我最终使用了SUDZC提供的同一个类

implementation was easy first I did an import 实施很容易我先做了一个导入

 #import "NSData+Base64.h"

then I was able to call my data. 然后我就能调用我的数据了。

 NSData *data = [[NSData alloc] initWithData:[NSData dataWithBase64EncodedString:strData]];

Or you may take a look to the (quite new) CryptoCompatibility sample project, I think there is a wrapper class for base64 operation. 或者您可以查看(非常新的) CryptoCompatibility示例项目,我认为有一个用于base64操作的包装类。 It is a MacOS sample but it uses the library libresolve.dylib with I think is available on iOS too (is see it at least here in iOS7). 它是一个MacOS示例,但它使用库libresolve.dylib,我认为也可以在iOS上使用(至少在iOS7中看到它)。

Be aware that there are more Base64 formats. 请注意,还有更多Base64格式。

For example JWTs use a URL safe format . 例如,JWT使用URL安全格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM