BASE64 decode function into Objective-C?

Discussion in 'iOS Programming' started by DT.DTDG, Sep 16, 2013.

  1. DT.DTDG macrumors newbie

    Sep 16, 2013
    I'm moving over from PHP and getting stuck into Objective-C.
    One thing I am trying to rewrite is a custom BASE64 function.

    How would this be written in Obj-C?

    public static function decode($string$key=hYc87.@.l_D3d-)
    $result '';
    $string str_replace(' ''+'$string);
    $string base64_decode($string);
    $string str_replace($key''$string);
    $i=0$i<strlen($string); $i++) {
    $char substr($string$i1);
    $keychar substr($key, ($i strlen($key))-11);
    $char chr(ord($char)-ord($keychar));
  2. Duncan C macrumors 6502a

    Duncan C

    Jan 21, 2008
    Northern Virginia

    I can't find any Base64 code that I'm free to share due to copyright/licensing issues.

    Erica Sadun's excellent "The Advanced iOS 6 Developer's cookbook" includes code in chapter 12, sample 0, that shows how to do the base 64 encoding/decoding, but I'm not sure if I'm free to post that code here for non-owners of the book.

    The code is a category of NSData that includes a class method to create NSData from a Base64 string and an instance method that will return the Base64 string for an NSData object.

    I suggest buying the book. It's chock-full of great resources like this. The
    "Core iOS 6 Developer's cookbook" title is excellent too. I highly recommend both to all working developers who use iOS.

    The books might not be the best choice for newbies, but for intermediate-to-advanced developers, they are invaluable. Within a few days of buying the previous iOS 5 title I found the solution to a problem that was dogging me for days, and the book paid for itself.
  3. PhoneyDeveloper, Sep 17, 2013
    Last edited: Sep 17, 2013

    PhoneyDeveloper macrumors 68040


    Sep 2, 2008
  4. DT.DTDG thread starter macrumors newbie

    Sep 16, 2013
    Thanks Duncan C and PhoneyDeveloper!

    I've sorted it out now :) it was basically the unicode vs byte1 representation from PHP to Objective-C..

    Thank you again!
  5. subsonix macrumors 68040

    Feb 2, 2008
    There are C libraries that does this as well, if you look at the examples at SO for example you'll see that many comments points out subtle bugs and memory leaks. A base64 encoder operates on primitive types, which makes it doable in C, an unsigned char is all you need.
  6. fxworker macrumors newbie

    Oct 16, 2013
    Hi DT.DTDG,

    it would be great, if you would share your working code here and give me the chance to learn from you.

    I´m also stuck in the same problem and need exactly the same.

    Many many thanks in advance.


Share This Page