Base64 Decoding in iOS 7+

128,769

Solution 1

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

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

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 

Solution 2

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];
Share:
128,769

Related videos on Youtube

Sandeep Khade
Author by

Sandeep Khade

"Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma - which is living with the results of other people's thinking. Don't let the noise of other's opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary" -Steve Jobs

Updated on June 02, 2020

Comments

  • Sandeep Khade
    Sandeep Khade almost 4 years

    I have Encoded text(NSString) using NSData Class new API which is Added in iOS7.

    using this

    - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding;  
    

    here is my code

    NSString *base64EncodedString = [[myText dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];
    
    NSLog(@"%@", base64EncodedString);
    

    I am looking to decode it

    • Carl Veazey
      Carl Veazey over 10 years
      m_EncodeText: please stop
    • user2159978
      user2159978 about 10 years
      where have you found base64EncodedStringWithOptions:?
    • Sandeep Khade
      Sandeep Khade about 10 years
    • user2159978
      user2159978 about 10 years
      It seems It happens when I use mac os console application target. Or the old version of sdk/mac os target
  • drlobo
    drlobo over 10 years
    I don't think this code is clean. I get the warning : "incompatible pointer types initializing NNSTring with an expression of NSData"
  • Bach
    Bach over 10 years
    @drlobo you must have typed base64EncodedDataWithOptions: instead of base64EncodedStringWithOptions:
  • Adam Waite
    Adam Waite about 10 years
    Thanks for this. Something I just found: a constant kNilOptions is equal to 0 which is arguably more readable than using 0 for options.
  • Gabriele Petronella
    Gabriele Petronella about 10 years
    @AdamWaite kNilOptions is defined in MacTypes.h which is a legacy OSX header, so I don't like using it, since I think that header should be removed from the iOS SDK altogether. Anyway, you have a point in saying that is very readable, so feel free to use it.
  • AlBeebe
    AlBeebe about 10 years
    I'm totally impressed with this answer. For years i've been using some ridiculous amount of code to decode a string, and all along there was a 2 line solution.
  • keisar
    keisar almost 10 years
    it seems the method base64EncodedStringWithOptions is not url safe base64
  • Micha Mazaheri
    Micha Mazaheri over 9 years
    This is awesome! Hacky, but awesome :)
  • shshnk
    shshnk over 9 years
    base64 decoding works only if the string length is a multiple of 4. otherwise NSData returns nil.
  • amit gupta
    amit gupta about 9 years
    this code works well But in my case i get xml response from server which are already in base64 encoded .I have decode that data but when i use this method it returns null. can anybody suggest me tackle this problem ???
  • jww
    jww almost 9 years
    Decoding may not work if there's a new line following the encoded data. See, for example, Decode base64 data encoded in bash.
  • Kumar C
    Kumar C almost 8 years
    I've never thought is is so easy! Thanks!!
  • spaceMonkey
    spaceMonkey almost 8 years
    if anyone getting a nil try NSDataBase64DecodingOptions.IgnoreUnknownCharacters i had this issue
  • Chris Prince
    Chris Prince almost 6 years
    I was decoding a JWT token, and learned there were a few more fancy steps to decode it. I used the method base64decode from github.com/Wstunes/SwiftyJWT after parsing the JWT token at the periods.