Show Menu

Looking to hire an app developer?

Submit your 30 day Job Listing for FREE

Here is a very quick tip that about Base64 decoding for iOS Applications and for Objective-C iOS7+, incl iOS8 Swift.

Knowing this quick reference has saved my bacon so many times, it might be a good idea to bookmark this page.

If you are just getting into iOS Swift Development, then check out these great resources:

Base64 Decoding in iOS 7+ for Objective-C


NSString *plainString = @"foo";

Encoding


NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding


NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Base64 Decoding in iOS 7+ for Swift


let plainString = "foo"

Encoding


let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) // Zm9v

Decoding


let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
println(decodedString) // foo 

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:


NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

I work in the shadows. You can thank me by being a good soul.

Comments

comments