Converting between NSData and base64 strings

后端 未结 6 980
野的像风
野的像风 2020-11-29 01:38

What is the easiest and fastest code to do a conversion between NSData and a base64 string? I\'ve read a bunch of solutions at SO and mostly they involve in add

相关标签:
6条回答
  • 2020-11-29 02:04

    Scroll down to the Conclusion section on the page you linked and download the provided NSData+Base64 files. 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.


    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.

    0 讨论(0)
  • 2020-11-29 02:04

    I ended up using this same class as provided by 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]];
    
    0 讨论(0)
  • 2020-11-29 02:05

    You don't need any custom implementation. Creating base64 from NSData is shown in other answers. There is opposite direction. From Base64 string to NSData:

     NSString *base64Encoded = @"some base64 string";
     NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];
    
    0 讨论(0)
  • 2020-11-29 02:10

    As of iOS 7, NSData now directly provides this functionality with the new methods -base64EncodedDataWithOptions: and -base64EncodedStringWithOptions:. (The options let you specify that the string is/should be line-wrapped, the better to deal with email, and user-facing displays.)

    0 讨论(0)
  • 2020-11-29 02:13

    Be aware that there are more Base64 formats.

    For example JWTs use a URL safe format.

    0 讨论(0)
  • 2020-11-29 02:13

    Or you may take a look to the (quite new) CryptoCompatibility sample project, I think there is a wrapper class for base64 operation. 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).

    0 讨论(0)
提交回复
热议问题