Monday, October 21, 2013

Base 64 conversion iOS Decoding



Lot a time its being needed that we have to encrypt the data before we transmit over air, for this iOS also provides support for encoding and decoding the string or data we want to transmit or receive into a an encrypted format. Most common mode for encoding as I know is Base64, it similar to other coding except all the bits are converted to Number system having base as 64(Just as Binary is base 2, octal is base 8). iOS itself provides very useful and efficient methods to convert between Base64 and other encodings. I have just tried to give a model class which will simply allow user to call the methods and get the desired output. This following code snippet is for Decoding Base64-NSData or Base64-NSString into Normal NSString or NSData.
       

@implementation NSString (Base64)
#import "Base64.h"

#import 

#if !__has_feature(objc_arc)

#error This library requires automatic reference counting

#endif
 

+ (NSString *)stringWithBase64EncodedString:(NSString *)string

{

    NSData *data = [NSDatadataWithBase64EncodedString:string];

    if (data)

    {

        return [[selfalloc] initWithData:data encoding:NSUTF8StringEncoding];

    }

    returnnil;

}

 

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth

{

    NSData *data = [selfdataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:YES];

    return [data base64EncodedStringWithWrapWidth:wrapWidth];

}

 

- (NSString *)base64EncodedString

{

    NSData *data = [selfdataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:YES];

    return [data base64EncodedString];

}

 

- (NSString *)base64DecodedString

{

    return [NSStringstringWithBase64EncodedString:self];

}

 

- (NSData *)base64DecodedData

{

    return [NSDatadataWithBase64EncodedString:self];

}

 @end

       
 

No comments:

Post a Comment