iOS 7: Base64 Encode and Decode NSData and NSString Objects
FRI, JAN 24
CORE SERVICES
TWEET
With the release of iOS 7, Apple added support for encoding and decoding data using Base64. In this post we will walk through two examples using Base64 to encode and decode both NSData and NSString objects.
First, we will create an NSString object that is generated by Base64 encoding an NSData object. This will be followed by decoding the Base64 NSString back into an NSData object. We will display the NSString data, both encoded and decoded to make sure all is well.
The second example will encode and decode NSData to/from Base64. This example is relevant if you have an NSData object that needs to be Base64 encoded, or you need to decode a Base64 NSData object (for whatever reason).
Create a Base64 Encoded NSString Object
Let’s begin by encoding an NSData object into Base64 and returning an NSString object:
1234567891011121314151617181920nsdata dataUsingEncoding:NSUTF8StringEncoding];base64Encoded ;// Print the Base64 encoded stringNSLog, base64Encoded);// Let’s go the other way…nsdataFromBase64String alloc] initWithBase64EncodedString;base64Decoded alloc] initWithData:nsdataFromBase64String encoding:NSUTF8StringEncoding];NSLog, base64Decoded);
On line 2 we create the NSData to encode. Line 6 encodes the data and returns an NSString object.
To go back the other way, from a Base64 encoded NSString object to an NSData object is as easy as calling the methodinitWithBase64EncodedString, passing in the Base64 encoded NSString (lines 14-15).
Lines 18-20 go from the Base64 NSData object back to an NSString (which is how we started this example, from a string).
The output looks as follows:
Encoded: aU9TIERldmVsb3BlciBUaXBzIGVuY29kZWQgaW4gQmFzZTY0Decoded: iOS Developer Tips encoded in Base64
Base64 Encode an NSData Object
There’s a good chance the NSString conversions (above) may be more about debugging than a day-to-day need to Base64 encoded strings. With that in mind, let’s look at how to directly encode an NSData object to Base64 as well as how to decode an NSData object from Base64.
123456789101112131415dataTake2 dataUsingEncoding:NSUTF8StringEncoding];base64Data ;NSLog, base64Data bytes;// Do something with the data// …nsdataDecoded ;alloc] initWithData:nsdataDecoded encoding:NSUTF8StringEncoding];NSLog, str);
On line 2 we create our NSData test subject. Line 6 we call thebase64EncodedDataWithOptionsmethod of the NSData class to Base64 encode the data. I’ve included an NSString conversion of the data solely to verify what goes in is the same as what comes back out.
Decoding the Base64 NSData object is nothing more than calling the methodinitWithBase64EncodedDatawith the encoded NSData object (line 13). Once again, I’ve included an NSString conversion for testing.
Additional Reading
,穿越茫茫人海,寻找属于我们的那一份宁静。