Monday, July 8, 2013

Convert NSData into Base 64 string for SOAP services

Currently i was working on a SOAP request and wanted to send a file on the server, i looked at the SOAP request and saw that one of the parameter in the SOAP service accepted base64 as parameter, so i wanted to convert the NSData into base64 so after a long time spending debugging and breaking heads i finally surfed up and came saw a solution on stackoverflow  which i would like to share with you 

+ (NSString*)base64forData:(NSData*)theData {
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;
            if (j < length) {
                value |= (0xFF & input[j]);
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];


The above function will convert the NSData into base64 string which you can send in your SOAP service as a parameter. And if you are finding it difficult to work with SOAP services then here's a link to my old tutorial on SOAP service.

Happy iCoding and have a great day.

Join Us on Facebook


  1. your Blog is awesome
    we are also iphone app developers and i would like to do link to your website if you feel good so?

  2. Helpful blog post, In the considering information and facts are and thus advantageous for everyone, Thought about cherished from your very own critical information

  3. Thanks for sharing such an useful and informative post. This coding is so helpful for developers.

  4. That is really good and useful blog, going to share it among my circle of friends so that they can also get benefit from it. Thank you for sharing it with us

  5. Though this blog is not helpful for everyone but for the people in IT and specially I phone app developers it will help them alot. I am not a programmer so i cannot understand the coding language but still your effort is appreciated. Good work...